using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using DICE_GS;
using System;
using System.IO;
using System.Linq;

#if UNITY_EDITOR
using UnityEditor;
#endif

[System.Serializable]
public class PacketReplayInfo
{
	public Dictionary<byte, object> packet;
	public float time;
	public PacketReplayInfo(float _time, Dictionary<byte, object> _packet)
	{
		packet = _packet;
		time = _time;
	}
}

public class StageManagerWrapper : MonoBehaviour 
{
    public static CStageManager Instance = new CStageManager();
	public static StageManagerWrapper manager;

	
    public static IDictionary<int, GameObject> objectMap;

	public static bool m_Connected = false;
	public static bool is_PVE;
	private static Queue<string> msgQueue;
    private static Queue<Dictionary<byte, object>> packetQueue;
	private static Queue<Dictionary<byte, object>> ForcePacketQueue;
	public static List<byte> packetTakenList;
	private static Queue<PacketReplayInfo> packetReplayInfo;
	public static bool bOrdered = false;
	public static bool bPlaying = false;
	public static bool isBoardManagerInit = false;
	public GameObject diceSet;
	public static DateTime combatRollDeadLine;
	public static int showUI_attackerID;
	public int rollCombatDiceSID;
	public int battleAIThinkingSID;
	public bool bAIBattleDiceRollImmediately;
	public byte [] battleDiceList;
	public static int showUI_defenderID;
    public static int m_MySID = 0;
	public static int myGameOrder = 0;
	public static int m_BossSID = 0;
	public static int nPCCount = 1;
	public static int totalPlayerCount = 0;
	public static int nAICount;
	public static int nPawnCreated;
	public static bool isAICreated;
	public static float createpawn_zoffset;
	public static bool bTurnStarted;
	public static bool bContinueTurnStarted;
	public static bool m_isMyTurn;
	public static List<int> NPCIdList;
	public float timeElapsedFromStart;
	public float replaySumTime;
	public float timeScale = 1.0f;
	public float replayLastTime;
	public int replayLastTurn;
	public bool bPauseAtTime;
	public float pauseTime;
	public bool bPauseAtTurn;
	public int pauseTurn;
	public bool bShowTimeElapsed;
	public int nPacketWaiting;
	string strPacketWaitingInfo;
	public bool bChangeBGMTimeLimit;
	public float timeToSwitchBGM = 300;
	public static int aiCharSelectNum = 0;
	public static CameraControl camControl;
	public int m_curTurn = 0;
	public UIPanel loadingPanel;
	public static bool bFindPathToGoal;
	public static bool bPathRun = false;
	public int combatInfo_attackerSID;
	public int combatInfo_defenderSID;
	public List<int> candidatePathBoard;
	public static int nTestCount = 0;
//	public static bool bTestCheckTexture;
	public static bool isGameOrdered;
//	public static PC_SC_CREATE_PAWN reserveCreatePawnPacket;
	public bool bWaitPacketForTutorial;
	static string strLog;
	public bool bShowPacketLog;
	public bool bPrepareTutorialReplay;
	public bool bSkipLog = true;

	void Awake()
	{
        MapEffectLight.SetMapEffectLight();
		manager = this;
		glog.debug ("StageManagerWrapper Awake ");
		isBoardManagerInit = false;
		packetReplayInfo = new Queue<PacketReplayInfo>();
		packetQueue = new Queue<Dictionary<byte, object>>();
		ForcePacketQueue = new Queue<Dictionary<byte, object>>();
		packetTakenList = new List<byte>();
		objectMap = new Dictionary<int, GameObject>();
		msgQueue = new Queue<string>();
		NPCIdList = new List<int>();
		candidatePathBoard = new List<int>();
		Instance.Method = EventHandlerForStageManagerWrapper;

        CNetworkManager.Instance.Method = EventHandlerForStageManagerWrapper;
		CNetworkManager.Instance.PacketHandler = PacketHandler;
#if UNITY_EDITOR
        CNetworkManager.Instance.Log = PrintLog;
#endif	
		//Instance.LoadSkillData(CSceneManager.Skill_data, true);
		//Instance.LoadUnitData(CSceneManager.Unit_data, true);
		replaySumTime = 0.0f;
		if(CSceneManager.isReplay)
		{
			SaveReplay(true);
			if(packetReplayInfo.Count>0)
			{
				replayLastTime = packetReplayInfo.LastOrDefault().time ;
			}			
		}

		if(CSceneManager.m_Scene>0 || CSceneManager.isReplay)
		{
			loadingPanel.gameObject.SetActive(true);		
			//StartCoroutine("CoLoadManagers");
		}
	}
	
	public static void SaveReplay(bool bLoad)
	{
		string dir = @"c:\temp";
#if UNITY_EDITOR || UNITY_WEBPLAYER
		Directory.CreateDirectory(dir);
#elif UNITY_IPHONE || UNITY_ANDROID
		dir = SystemCore.GetAssetPath()+"/";
#endif
		Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes");
		
		if(!bLoad)
		{
			// save remaining packet
//			foreach (Dictionary<byte, object> tmpPacket in packetQueue)
//			{
//				packetReplayInfo.Enqueue( new PacketReplayInfo(Time.timeSinceLevelLoad, tmpPacket) );
//			}

			if(File.Exists(Path.Combine(dir, "replayDice.bin")))
			{
				FileInfo fi = new FileInfo(Path.Combine(dir, "replayDice.bin"));
				File.Move(Path.Combine(dir, "replayDice.bin"), Path.Combine(dir, String.Format("{0}\\replayDice_{1}_{2}_{3}_{4}_{5}_{6}_{7}.bin", dir, DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second, DateTime.Now.Millisecond)));
			}
		}
        string serializationFile = Path.Combine(dir, "replayDice.bin");
		
		if(!bLoad)
		{

	        //serialize
	        using (Stream stream = File.Open(serializationFile, FileMode.Create))
	        {
	            var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
				bformatter.Serialize(stream, CSceneManager.m_mapName);
				bformatter.Serialize(stream, CSceneManager.m_themeType);
				//bformatter.Serialize(stream, CSceneManager.charSelected);
	            bformatter.Serialize(stream, packetReplayInfo);
	        }		
		}
		else
		{
			if(CSceneManager.isIngameTutorial)
			{
				GameObject replayGoPrefab = Resources.Load("Prefabs/Replay/tutorial_1") as GameObject;
				if(replayGoPrefab!=null)
				{
					GameObject replayGo = Instantiate(replayGoPrefab) as GameObject;
					ReplayInfo rInfo = replayGo.GetComponent<ReplayInfo>();
					/*CSceneManager.m_mapName = rInfo.mapName;
					CSceneManager.m_themeType = rInfo.mapElementType;
//					//packetReplayInfo = rInfo.packetReplayInfo;
					foreach(PacketReplayInfo prInfo in rInfo.packetReplayInfo)
					{
						packetReplayInfo.Enqueue(prInfo);
					}*/
					using (Stream stream = new MemoryStream(rInfo.byteData) )
					{
						var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
						CSceneManager.m_mapName = (string)bformatter.Deserialize(stream);
						CSceneManager.m_themeType = (element)bformatter.Deserialize(stream);

						packetReplayInfo = (Queue<PacketReplayInfo>)bformatter.Deserialize(stream);
					}
				}
				else
					Debug.LogError("tutoriak replay not found");
			}
			else
			{
		        //deserialize
		        using (Stream stream = File.Open(serializationFile, FileMode.Open))
		        {
		            var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
					CSceneManager.m_mapName = (string)bformatter.Deserialize(stream);
					CSceneManager.m_themeType = (element)bformatter.Deserialize(stream);
		            packetReplayInfo = (Queue<PacketReplayInfo>)bformatter.Deserialize(stream);
		        }
			}

		}
		glog.debug("packetreplayinfo "+packetReplayInfo.Count+"   "+CSceneManager.m_mapName);
		
		if (!bLoad)
		{
			using (MemoryStream stream = new MemoryStream())
			{
				var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
				bformatter.Serialize(stream, CSceneManager.m_mapName);
				bformatter.Serialize(stream, CSceneManager.m_themeType);
				bformatter.Serialize(stream, packetReplayInfo);

				StreamReader reader = new StreamReader(stream);
#if UNITY_EDITOR
				//for tutorial asset save
				if(manager.bPrepareTutorialReplay)
				{
					GameObject replayGo = new GameObject();
					replayGo.name = "replay_"+ ((int)Time.timeSinceLevelLoad).ToString();
					ReplayInfo rInfo = replayGo.AddComponent<ReplayInfo>();
					rInfo.mapName = CSceneManager.m_mapName;
					rInfo.mapElementType = CSceneManager.m_themeType;
					rInfo.byteData = stream.ToArray();
					/*
					foreach ( PacketReplayInfo pInfo in packetReplayInfo)
					{
						PacketReplayInfo newPInfo = new PacketReplayInfo(pInfo.time, new Dictionary<byte, object>(pInfo.packet));
						//newPInfo.time = pInfo.time;
						//newPInfo.packet = new Dictionary<byte, object>(pInfo.packet);
						rInfo.packetReplayInfo.Add(newPInfo);
					}*/
					
					UnityEngine.Object prefab = PrefabUtility.CreateEmptyPrefab("Assets/Resources/Prefabs/Replay/tutorial_1.prefab");
					PrefabUtility.ReplacePrefab(replayGo, prefab, ReplacePrefabOptions.ConnectToPrefab);
					AssetDatabase.SaveAssets();
				}
#endif
                PC_CS_SAVE_REPLAY packet = new PC_CS_SAVE_REPLAY();

				string Version = "";

				string[] a = System.Reflection.Assembly.GetAssembly(packet.GetType()).FullName.Split(' ');

				foreach (string s in a)
				{
					if (s.Trim().StartsWith("Version"))
					{
						Version = s.Split('=', ',')[1];
						break;
					}
				}

				packet.Version = Version;
				packet.Length = (int)stream.Length;
				packet.Context = stream.ToArray();

				CNetworkManager.Instance.SendPacket(packet);
			}		
		}
	}

	
    void Start()
    {
		camControl = Camera.main.gameObject.GetComponent<CameraControl>();
		if(CSceneManager.m_Scene>0  || CSceneManager.isReplay)
			StartCoroutine("CoLoadManagers");
    }

	IEnumerator CoLoadManagers()
	{
		string [] managerNames = {
			"EffectManager", "SoundManager", "BoardManager" };
		
		foreach(string managerName in managerNames)
		{
			string strText = "Loading...";//+managerName;
			loadingPanel.GetComponentInChildren<UILabel>().text = strText;
			glog.debug(strText);
			float timeStart = Time.time;
			GameObject tmePrefab = Resources.Load("Prefabs/Manager/" + managerName) as GameObject;
			if(tmePrefab!=null)
			{
	        	GameObject _tmpObj = Instantiate(tmePrefab) as GameObject;
				if(_tmpObj==null)
					Debug.LogError("managerName not exist "+managerName);
			}
			glog.debug("Loading done  "+managerName+"     "+(Time.time-timeStart).ToString("0.00") );
			yield return null;
		}
	}	
	
	public static void SendLeave()
	{
		glog.debug("SendLeave");

        PC_OP_LEAVE packet = new PC_OP_LEAVE();
		CNetworkManager.Instance.SendPacket(packet);
		ClearStage();
	}
	
	public static void ClearStage()
	{
		glog.debug ("ClearStage");

		if (objectMap != null)
		{
			objectMap.Clear();
			Instance.ClearStage();
		}
		//Add by HyunSeung. 2013.10.02
		//When maingame wasn't played, "null exception" is appeared.
		if( MainHUDUI.Instance != null )
			MainHUDUI.Instance.ClearTeam();
		nAICount = 0;
		nPCCount = 1;
		totalPlayerCount = 0;
		aiCharSelectNum = 0;
		nPawnCreated = 0;
		bTurnStarted = false;
		bContinueTurnStarted = false;
        if( BoardManager.Instance != null )
		    BoardManager.Instance.isShowDiceUIDone = true;
		m_BossSID = 0;
		if( NPCIdList != null )
			NPCIdList.Clear();
		isGameOrdered = false;
		bFindPathToGoal = false;
		PvPMakeRoomSceneManager.isMakeRoom = false;
		RuntimeLog.Clear();
		if(BoardTile.movingCourseList!=null)
			BoardTile.movingCourseList.Clear();
		if(BoardTile.tileElementEffectList!=null)
			BoardTile.tileElementEffectList.Clear ();
		if(CSceneManager.m_Scene == SCENE.InGameScene)
		{
			SoundManagerCommon.Instance.StopBGM();
			SoundManagerCommon.Instance.PlayBGM(2);		
		}
		System.GC.Collect();
	}
	
	void HideDiceSet()
	{
		diceSet.SetActive(false);	
	}
	
	bool ShouldWaitPacketForBattle(byte code)
	{
		if(bWaitPacketForTutorial)
			return true;
		if( code == (byte)OperationCodes.OP_TURN_ALRAM)
			return true;
		if( code == (byte)OperationCodes.OP_MOVE_FORWARD)
			return true;
		if( code == (byte)OperationCodes.SC_CREATE_PAWN)
			return true;
		
		if( code == (byte)OperationCodes.OP_GAME_OVER)
			return true;
		
		if( !BattleManager.Instance.isBattleResultDone && code == (byte)OperationCodes.OP_MOVE_BACKWARD)
			return true;
		
		if( !BattleManager.Instance.isBattleResultDone && code == (byte)OperationCodes.OP_DELETE_PAWN_FROM_GAME)
			return true;
		
		if( !BattleManager.Instance.isBattleResultDone && code == (byte)OperationCodes.OP_COMBAT_INFO)
			return true;
		
		if( code == (byte)OperationCodes.OP_TELEPORT_PAWN)
			return true;

		if( BoardManager.Instance.bWaitForUIBattleDice    )
		{
			if(code == (byte)OperationCodes.SC_ROLL_COMBAT_DICE_RESULT || code == (byte)OperationCodes.SC_HIDE_UI || code == (byte)OperationCodes.OP_CHANGE_PAWN_TYPE)
				return false;
			else if(code == (byte)OperationCodes.OP_USE_SKILL || code == (byte)OperationCodes.OP_USE_TEMP_SKILL || code == (byte)OperationCodes.OP_USE_ITEM || code == (byte)OperationCodes.OP_UPDATE_TEAM_DATA)
				return false;

			else
				return true;
		}

		return false;
	}
	bool ShouldWaitPacketForAfterBattle(byte code)
	{
		if(bWaitPacketForTutorial)
			return true;
		if(code == (byte)OperationCodes.OP_TURN_ALRAM)
		{
			if( BoardManager.Instance.isBoardPersonMoving )
				return true;
			if( !BoardManager.Instance.nextTurnOK)
				return true;			
		}

		if( BoardManager.Instance.bWaitForDirectionRollDone )
			return true;

		if( BoardManager.Instance.bWaitForUIBattleDice    )
		{
			if(code == (byte)OperationCodes.SC_ROLL_COMBAT_DICE_RESULT || code == (byte)OperationCodes.SC_HIDE_UI || code == (byte)OperationCodes.OP_CHANGE_PAWN_TYPE)
				return false;
			else if(code == (byte)OperationCodes.OP_USE_SKILL || code == (byte)OperationCodes.OP_USE_TEMP_SKILL || code == (byte)OperationCodes.OP_USE_ITEM || code == (byte)OperationCodes.OP_UPDATE_TEAM_DATA)
				return false;
			else
				return true;
		}

		return false;
	}
	
	bool ShouldWaitPacket(byte code)
	{
		if(bWaitPacketForTutorial)
			return true;
		if(code == (byte)OperationCodes.OP_TURN_ALRAM)
		{
			if( BoardManager.Instance.isBoardPersonMoving || BoardManager.Instance.isWaitingForBoardPersonMoving)
				return true;
			if( !BoardManager.Instance.nextTurnOK)
				return true;
		}
		
		//for boss destroy and collect unit in game
		if( (BoardManager.Instance.isBoardPersonMoving || BoardManager.Instance.isWaitingForBoardPersonMoving) && code == (byte)OperationCodes.OP_DELETE_PAWN_FROM_GAME )
			return true;
		
		//for boss destroy and collect unit in game
		if( (BoardManager.Instance.isBoardPersonMoving || BoardManager.Instance.isWaitingForBoardPersonMoving) && code == (byte)OperationCodes.SC_ADD_TEAM_DATA )
			return true;
	
		if( (BoardManager.Instance.isBoardPersonMoving || BoardManager.Instance.isWaitingForBoardPersonMoving) && code == (byte)OperationCodes.OP_GAME_OVER )
			return true;
		
		if( BoardManager.Instance.bUsedTeleportSkill && code == (byte)OperationCodes.OP_ROLL_MOVE_DICE_RESULT )
			return true;
		
		if( BoardManager.Instance.bWaitForSkillShow)
			return true;

		if( BoardManager.Instance.bWaitForDirectionRollDone )
			return true;

		if( BoardManager.Instance.bWaitForUIBattleDice    )
		{
			if(code == (byte)OperationCodes.SC_ROLL_COMBAT_DICE_RESULT || code == (byte)OperationCodes.SC_HIDE_UI || code == (byte)OperationCodes.OP_CHANGE_PAWN_TYPE)
				return false;
			else if(code == (byte)OperationCodes.OP_USE_SKILL || code == (byte)OperationCodes.OP_USE_TEMP_SKILL || code == (byte)OperationCodes.OP_USE_ITEM || code == (byte)OperationCodes.OP_UPDATE_TEAM_DATA)
				return false;
			else
				return true;
		}

		return false;
	}	

	static bool IsForcePacket(byte packet_code)
	{
		if( packet_code == (byte)OperationCodes.OP_EMOTION_CHAT || packet_code == (byte)OperationCodes.SC_DEBUG_MSG || packet_code == (byte)OperationCodes.OP_CONTINUE_PLAY ||
		   packet_code == (byte)OperationCodes.SC_ACHIEVEMENT_COMPLETE || packet_code == (byte)OperationCodes.SC_GIVE_UP_GAME || packet_code == (byte)OperationCodes.OP_CHANGE_PAWN_TYPE )
			return true;
		return false;
	}

	void ProcessForcePacketQueue(Dictionary<byte, object> tmpPacket)
	{
		switch ((byte)tmpPacket[0])
		{
			case (byte)OperationCodes.OP_EMOTION_CHAT:
			{
				Debug.LogError("Showing Emoticon");
				PC_OP_EMOTION_CHAT packet = new PC_OP_EMOTION_CHAT(tmpPacket);
				HudManager.Instance.ShowUserEmotionChat(packet.ServerID, int.Parse(packet.Message));
				break;
			}
			case (byte)OperationCodes.SC_DEBUG_MSG:
			{
				
				break;
			}
			case (byte)OperationCodes.OP_CONTINUE_PLAY:
			{
				PC_OP_CONTINUE_PLAY packet = new PC_OP_CONTINUE_PLAY(tmpPacket);
				glog.debug("************ OP_CONTINUE_PLAY SID=" + packet.ServerID);
				//GetBoardPerson(packet.ServerID).SetRetire( false);
				
				GetBoardPerson(packet.ServerID).bContinueFromRetire = true;
				break;
			}
			case (byte)OperationCodes.SC_ACHIEVEMENT_COMPLETE:
			{
				PC_SC_ACHIEVEMENT_COMPLETE packet = new PC_SC_ACHIEVEMENT_COMPLETE(tmpPacket);
				Debug.LogError("** SC_ACHIEVEMENT_COMPLETE SID=" + packet.ServerID+"  "+packet.AchievementID);
				if (packet.ServerID == m_MySID)
				{                        
					UIManager.Instance.TestShowAchievement(packet.AchievementID);
				}
				break;
			}
			case (byte)OperationCodes.SC_GIVE_UP_GAME:
			{
				UIManager.Instance.CreateSelectRewardUI(true);		
				break;
			}
				
			case (byte)OperationCodes.OP_CHANGE_PAWN_TYPE:
			{
				PC_OP_CHANGE_PAWN_TYPE packet = new PC_OP_CHANGE_PAWN_TYPE(tmpPacket);
				CPawn tmpPawn = Instance.FindPawn(packet.ServerID);
				
				if (tmpPawn != null)
				{
					if(packet.PawnType == (int)GAME_PAWN_TYPE.PC)
					{
						GetBoardPerson(packet.ServerID).pawnType = GAME_PAWN_TYPE.PC;
						HudManager.Instance.SetBotMark(packet.ServerID, false);
						tmpPawn.ChangePawnToPC();
					}
					else if (packet.PawnType == (int)GAME_PAWN_TYPE.BOT)
					{
						GetBoardPerson(packet.ServerID).pawnType = GAME_PAWN_TYPE.BOT;
						HudManager.Instance.SetBotMark(packet.ServerID, true);
						tmpPawn.ChangePawnToBOT();
					}
				}
				
				if (objectMap[packet.ServerID].GetComponent<BoardPerson>().isMe)
				{
					if (packet.PawnType == (int)GAME_PAWN_TYPE.PC)
					{
						CSceneManager.BOTIsOn = false;
					}
					else if (packet.PawnType == (int)GAME_PAWN_TYPE.BOT)
					{
						CSceneManager.BOTIsOn = true;
					}
				}
				break;
			}
				
			default:
				glog.debug("ForcePacketQueue Unknown Packet Recieved [" + (OperationCodes)tmpPacket[0] +"]");
				break;
		}
	}

	void Update()
	{
		if(!isBoardManagerInit)
		{
			//glog.debug ("StageManager did not init");
			return;
		}
		/*  */
		if(msgQueue.Count > 0)
		{
			string msg = msgQueue.Dequeue();
			
            if (msg.Split(';')[0].Equals("MakeOrder"))
	        {
	            bOrdered = true;
	        }
	        if (msg.Split(';')[0].Equals("PlayStart"))
	        {
	            bPlaying = true;
	        }			
//			if(msg.Split(';')[0] == "Dice")
//			{
//				int nDice = int.Parse(msg.Split(';')[2]);
//                int nAddNum = int.Parse(msg.Split(';')[3]);
//				BoardManager.Instance.ShowDiceUI(nDice, nAddNum);
//			}
		}

		Time.timeScale = timeScale;
		timeElapsedFromStart = Time.timeSinceLevelLoad;

//		if(timeElapsedFromStart>= timeToSwitchBGM)
//		{
//			if(!bChangeBGMTimeLimit)
//			{
//				bChangeBGMTimeLimit = true;
//				SoundManagerCommon.Instance.PlayBGM(1);
//			}
//		}
		
		if(CSceneManager.isReplay)
		{
			replaySumTime += Time.deltaTime;
			if(bPauseAtTime)
			{
				if(replaySumTime>=pauseTime)
					Debug.Break();
			}
		}

		while (ForcePacketQueue.Count > 0  )
		{
			Dictionary<byte, object> tmpPacket = null;
			tmpPacket = ForcePacketQueue.Dequeue();
			//packetReplayInfo.Enqueue( new PacketReplayInfo(Time.timeSinceLevelLoad, tmpPacket) );
			ProcessForcePacketQueue(tmpPacket);
		}
		
		while (packetQueue.Count > 0 || (CSceneManager.isReplay && packetReplayInfo.Count>0) )
        {
			if(bFindPathToGoal)
				break;

			/// check packet waiting
			if(BattleManager.Instance.bCombatHappened )
			{
				if( !BattleManager.Instance.isWinnerActionDone || !BattleManager.Instance.isLoserActionDone) 
				{
					if(CSceneManager.isReplay)
					{
						Dictionary<byte, object> peekPacket = packetReplayInfo.Peek().packet;
						byte packet_code = (byte) peekPacket[0];
						if( ShouldWaitPacketForBattle( packet_code  ) )
						{
							int	nWaitingPacketCount = packetReplayInfo.Count;
							nPacketWaiting++;
							OperationCodes opcode = (OperationCodes) packet_code;
							if(CSceneManager.bShowPacketWaitingInfo)
								strPacketWaitingInfo = String.Format(opcode.ToString()+"      Waiting...  {0:0000}     {1:0000}", nPacketWaiting, nWaitingPacketCount);
							break;
						}					
					}
					else
					{
						Dictionary<byte, object> peekPacket = packetQueue.Peek();
						byte packet_code = (byte) peekPacket[0];
						if( ShouldWaitPacketForBattle( packet_code  ) )
						{
							int nWaitingPacketCount = packetQueue.Count;
							nPacketWaiting++;
							OperationCodes opcode = (OperationCodes) packet_code;
							if(CSceneManager.bShowPacketWaitingInfo)
								strPacketWaitingInfo = String.Format(opcode.ToString()+"     Waiting...  {0:0000}     {1:0000}", nPacketWaiting, nWaitingPacketCount);
							break;
						}					
					}
				}
				else// after battle move
				{
					if(CSceneManager.isReplay)
					{
						Dictionary<byte, object> peekPacket = packetReplayInfo.Peek().packet;
						byte packet_code = (byte) peekPacket[0];
						if( ShouldWaitPacketForAfterBattle( packet_code  ) )
						{
							int	nWaitingPacketCount = packetReplayInfo.Count;
							nPacketWaiting++;
							OperationCodes opcode = (OperationCodes) packet_code;
							if(CSceneManager.bShowPacketWaitingInfo)
								strPacketWaitingInfo = String.Format(opcode.ToString()+"      Waiting...  {0:0000}     {1:0000}", nPacketWaiting, nWaitingPacketCount);
							break;
						}					
					}
					else
					{
						Dictionary<byte, object> peekPacket = packetQueue.Peek();
						byte packet_code = (byte) peekPacket[0];
						if( ShouldWaitPacketForAfterBattle( packet_code  ) )
						{
							int nWaitingPacketCount = packetQueue.Count;
							nPacketWaiting++;
							OperationCodes opcode = (OperationCodes) packet_code;
							if(CSceneManager.bShowPacketWaitingInfo)
								strPacketWaitingInfo = String.Format(opcode.ToString()+"     Waiting...  {0:0000}     {1:0000}", nPacketWaiting, nWaitingPacketCount);
							break;
						}					
					}					
				}

			}
			else
			{
				if(CSceneManager.isReplay)
				{
					Dictionary<byte, object> peekPacket = packetReplayInfo.Peek().packet;
					byte packet_code = (byte) peekPacket[0];
					if( ShouldWaitPacket( packet_code  ) )
					{
						int	nWaitingPacketCount = packetReplayInfo.Count;
						nPacketWaiting++;
						OperationCodes opcode = (OperationCodes) packet_code;
						if(CSceneManager.bShowPacketWaitingInfo)
							strPacketWaitingInfo = String.Format(opcode.ToString()+"      Waiting...  {0:0000}     {1:0000}", nPacketWaiting, nWaitingPacketCount);
						break;
					}					
				}
				else
				{
					Dictionary<byte, object> peekPacket = packetQueue.Peek();
					byte packet_code = (byte) peekPacket[0];
					if( ShouldWaitPacket( packet_code  ) )
					{
						int nWaitingPacketCount = packetQueue.Count;
						nPacketWaiting++;
						OperationCodes opcode = (OperationCodes) packet_code;
						if(CSceneManager.bShowPacketWaitingInfo)
							strPacketWaitingInfo = String.Format(opcode.ToString()+"     Waiting...  {0:0000}     {1:0000}", nPacketWaiting, nWaitingPacketCount);
						break;
					}					
				}				
			}
			//////

			strPacketWaitingInfo = "";
			nPacketWaiting = 0;
			Dictionary<byte, object> tmpPacket = null;

			if(CSceneManager.isReplay)
			{
				//replaySumTime += Time.deltaTime;
				if(packetReplayInfo.Count>0)
				{
					PacketReplayInfo replayInfoPeek = packetReplayInfo.Peek();
					if(replaySumTime >= replayInfoPeek.time )
					{
						PacketReplayInfo replayInfo = packetReplayInfo.Dequeue();
						glog.debug("dequeue replay packet "+replaySumTime+"  "+replayInfo.time);
						tmpPacket = replayInfo.packet;
						if(tmpPacket!=null)
							WriteToRuntimeLog( (byte)tmpPacket[0]);
					}
				}
				if(tmpPacket==null)
					break;
			}
			else
			{
				tmpPacket = packetQueue.Dequeue();
				//packetReplayInfo.Enqueue( new PacketReplayInfo(Time.timeSinceLevelLoad, tmpPacket) );
			}

            Debug.LogWarning("<color=RED>" +( (OperationCodes)((byte)tmpPacket[0]) ).ToString() + "</color>");
            switch ((byte)tmpPacket[0])
			{
				#region OperationCodes.OP_ROLL_MOVE_DICE_RESULT:
				case (byte)OperationCodes.OP_ROLL_MOVE_DICE_RESULT:
                    {
                        PC_OP_ROLL_MOVE_DICE_RESULT packet = new PC_OP_ROLL_MOVE_DICE_RESULT(tmpPacket);
                        if (!IsPawnCreated(packet.ServerID))
                            break;

                        if (!GetBoardPerson(packet.ServerID).isMe)
                        {
                            // 희소 상대편 시간컨트롤
							HudManager.Instance.StopGageAni(packet.ServerID);
                        }
			
						PP_RollMoveDiceResult(packet);
                    }
                    break;
                 #endregion				
                #region OperationCodes.SC_CHANGE_GAME_STATUS:
                case (byte)OperationCodes.SC_CHANGE_GAME_STATUS:
                    {
                        PC_SC_CHANGE_GAME_STATUS packet = new PC_SC_CHANGE_GAME_STATUS(tmpPacket);

                        StageManagerWrapper.Instance.SetStatus((GameStatus)packet.Status);
                        glog.debug("GStatus:" + (byte)StageManagerWrapper.Instance.Status);
                    }
                    break;
                 #endregion
                #region OperationCodes.SC_CREATE_PAWN:
                case (byte)OperationCodes.SC_CREATE_PAWN:
                    {
                        PC_SC_CREATE_PAWN packet = new PC_SC_CREATE_PAWN(tmpPacket);
						glog.debug ("createPawn sid= "+packet.ServerID+" MasterUnitID= " + packet.MasterUnitID+ "  type="+packet.PawnType+" curboard="+packet.CurrentBoard);
						CreateNewRunner(packet);
						if(packet.IsMaster)
						{					
							SkillManager.Instance.skillID_1 = packet.Skill_1st;
							SkillManager.Instance.skillID_2 = packet.Skill_2nd;
							SkillManager.Instance.skillID_3 = packet.Skill_3rd;
							SkillManager.Instance.skillID_4 = packet.Skill_4th;
							UIManager.Instance.SetSkillAndItem();
						}
                    }
                    break;
                #endregion
                #region OperationCodes.SC_SHOW_UI:
                case (byte)OperationCodes.SC_SHOW_UI:
                    {
                        PC_SC_SHOW_UI packet = new PC_SC_SHOW_UI(tmpPacket);
						ProcessShowUI(packet);
                    }
                    break;
                #endregion
                #region OperationCodes.SC_HIDE_UI:
                case (byte)OperationCodes.SC_HIDE_UI:
                    {

                        PC_SC_HIDE_UI packet = new PC_SC_HIDE_UI(tmpPacket);
                        Debug.LogWarning("<color=YELLOW>hide " + ((UIType)packet.UIType).ToString() + "</color>");
                       
                        if (packet.UIType == (int)UIType.UI_ROLL_MOVE_DICE)
                        {
                            //BoardManager.Instance.waitingTurnUI.SetActive(true);
                            UIManager.Instance.ShowMoveRollButton(false);
							UIManager.Instance.curDiceShape = DiceShapeType.None;
							if (CSceneManager.BuilderIsOn)
							{
								CSceneManager.BuilderStatus = 0;
							}
                        }

                        if (packet.UIType == (int)UIType.UI_ROLL_DIRECTION_DICE || packet.UIType == (int)UIType.UI_ROLL_ATTACK_DICE || packet.UIType == (int)UIType.UI_ROLL_DEFENCE_DICE)
                        {
							UIManager.Instance.curDiceShape = DiceShapeType.None;
                            if (CSceneManager.BuilderIsOn)
                            {
                                CSceneManager.BuilderStatus = 0;
                            }
                        }
                    }
                    break;
                #endregion
                #region OperationCodes.OP_MOVE_BACKWARD:
                case (byte)OperationCodes.OP_MOVE_BACKWARD:
                    {
                        PC_OP_MOVE_BACKWARD packet = new PC_OP_MOVE_BACKWARD(tmpPacket);
						if( !IsPawnCreated(packet.ServerID) )
						{
							glog.debug(packet.ServerID+" MOVE BACK loss", LOGCOLOR.MAGNETA);
							break;
						}
						if (packet.Path.Length > 0)
						{
							glog.debug("sid=" + packet.ServerID + "## From Server : move Back to " + packet.Path[packet.Path.Length - 1]);
						}
						else
						{
							glog.debug("sid=" + packet.ServerID + "## From Server : PathLength is 0 or minus");
						}
                        //Camera.main.gameObject.GetComponent<CameraControl>().SetCameraFocus(objectMap[packet.ServerID].transform);

                        BoardManager.Instance.StartMovePawn(objectMap[packet.ServerID].GetComponent<BoardPerson>(), packet.MoveCount, packet.Path, true);
                    }
                    break;
                #endregion
                #region OperationCodes.OP_MOVE_FORWARD:
                case (byte)OperationCodes.OP_MOVE_FORWARD:
                    {
				
                        PC_OP_MOVE_FORWARD packet = new PC_OP_MOVE_FORWARD(tmpPacket);
						if( !IsPawnCreated(packet.ServerID) )
							break;
						
						UIManager.Instance.ShowMoveRollButton(false);
						UIManager.Instance.DestroyPathSelectUI(0);
                        Camera.main.gameObject.GetComponent<CameraControl>().SetCameraFocus(objectMap[packet.ServerID].transform);
						BoardPerson person = objectMap[packet.ServerID].GetComponent<BoardPerson>();		
						if(packet.MoveCount>0) {
							glog.debug (String.Format("sid={0}  {1}  ## From Server : move forward from {2} to {3} MoveCount={4}",packet.ServerID, person.moveState, packet.Path[0], packet.Path[packet.MoveCount-1], packet.MoveCount) );
							if(person.bChasing)
								person.chaseStartBoardID = packet.Path[0];
						}
						else
							glog.debug ("sid="+packet.ServerID+" "+person.moveState+" ## From Server : move forward movecount zero");
						person.remainMoveCount = person.remainMoveCount - packet.MoveCount;
						
						if(person.moveState == BoardPerson.MoveState.Moving || person.moveState == BoardPerson.MoveState.WaitMoving)
							person.AddPath( packet.MoveCount, packet.Path);
						else {
                        	BoardManager.Instance.StartMovePawn(person, packet.MoveCount, packet.Path , false);
						}
                    }
                    break;
                #endregion
                #region OperationCodes.OP_COMBAT_RESULT:
                case (byte)OperationCodes.OP_COMBAT_RESULT:
                    {
                        PC_OP_COMBAT_RESULT packet = new PC_OP_COMBAT_RESULT(tmpPacket);
						if( !IsPawnCreated(packet.WinnerID) || !IsPawnCreated(packet.LoserID))
							break;

						ProcessCombatResult(packet);
                    }
                    break;
                #endregion				
                #region OperationCodes.OP_GAME_OVER:
                case (byte)OperationCodes.OP_GAME_OVER:
                    {
                        PC_OP_GAME_OVER packet = new PC_OP_GAME_OVER(tmpPacket);
						//if( !IsPawnCreated(packet.WinnerID) )
						//	break;
                        glog.debug("gameover execute  winnerId="+packet.WinnerID);
                        
						if( packet.WinnerID == m_MySID) {
							glog.debug("Win!");
							BoardManager.Instance.isWinGame = true;
						}
						else {
							glog.debug("Lose!");
							BoardManager.Instance.isWinGame = false;
						}
                        
						BoardManager.Instance.isGameOver = true;
						bool isPvpRoom = true;
						if(packet.RoomType==1)
							isPvpRoom = false;
						GameOverType gameOverType = (GameOverType)packet.GameOverType;
						BoardManager.Instance.ShowGameOver(isPvpRoom, packet.RunnerCount, packet.RankList, packet.RunnerIDList, packet.PVPRankPointList, packet.PVPRankPointDeltaList, gameOverType);				
						UIManager.Instance.HideRebirthWindow();
                    }
                    break;
                #endregion
                #region OperationCodes.OP_GAME_ORDER:
                case (byte)OperationCodes.OP_GAME_ORDER:
                    {
						PC_OP_GAME_ORDER packet = new PC_OP_GAME_ORDER(tmpPacket);
						isGameOrdered = true;
						for (int i = 0; i < packet.PawnCount; i++)
						{
							if(packet.PawnSIDList[i]==m_MySID)
								myGameOrder = (i+1);
						}
						for (int i = 0; i < packet.PawnCount; i++)
						{
							glog.debug("Game Order   ["+(i+1)+"] ---- ["+ packet.PawnSIDList[i] +"]");
							bool isBoss = false;
							if( packet.PawnSIDList[i] == m_BossSID )
								isBoss = true;
							GetBoardPerson(packet.PawnSIDList[i]).SetGameOrder(i+1);
							//HudManager.Instance.ChangeByGameOrder( GetBoardPerson(packet.PawnSIDList[i]), packet.PawnSIDList[i], (i+1) , isBoss);
						}
						int nPawnCount=packet.PawnCount;
						int totalCount=nPawnCount;
						int nGameOrder = myGameOrder;
						int createOrder = 1;
						while(totalCount>0)
						{
							HudManager.Instance.ChangeByGameOrder( nGameOrder, createOrder);
							createOrder++;
							totalCount--;
							nGameOrder++;
							if(nGameOrder>nPawnCount)
								nGameOrder=1;
						}
						BoardManager.Instance.isShowDiceUIDone = true;//for ai freeze at first turn
                    }
                    break;
                #endregion
                #region OperationCodes.OP_LEAVE:
                case (byte)OperationCodes.OP_LEAVE:
                    {
                        //PC_OP_LEAVE packet = new PC_OP_LEAVE(tmpPacket);

                        if (Instance.Status == GameStatus.GS_GAMEOVER)
                        {
                            LoadingWindow.window.ShowShortLoading();
                            RestAPI.singleton.RefreshUserData(ReturnCallback);
                            RestAPI.singleton.GetPVEStageInfo(ReturnCallback);
                        }

                        //CSceneManager.NeedToDisconnect = true;
                       // CNetworkManager.Instance.Disconnect();
                    }
                    break;
                #endregion
                #region OperationCodes.SC_SHOW_CHANGE_HP:
                case (byte)OperationCodes.SC_SHOW_CHANGE_HP:
					{
		                PC_SC_SHOW_CHANGE_HP packet = new PC_SC_SHOW_CHANGE_HP(tmpPacket);
						if( !IsPawnCreated(packet.ServerID) )
							break;
						ProcessShowChangeHP(packet);
					}
					break;
				#endregion
                #region OperationCodes.SC_SHOW_CHANGE_MP:
                case (byte)OperationCodes.SC_SHOW_CHANGE_MP:
                    {
                        PC_SC_SHOW_CHANGE_MP packet = new PC_SC_SHOW_CHANGE_MP(tmpPacket);
                       	if (!IsPawnCreated(packet.ServerID))
                            break;
						ProcessShowChangeMP(packet);
						
                    }
                    break;
                #endregion
				#region OperationCodes.OP_UPDATE_TEAM_DATA:
				case (byte)OperationCodes.OP_UPDATE_TEAM_DATA:
                    {
						PC_OP_UPDATE_TEAM_DATA packet = new PC_OP_UPDATE_TEAM_DATA(tmpPacket);
						if( !IsPawnCreated(packet.ServerID) )
							break;
						if(!bTurnStarted && !bContinueTurnStarted && packet.ServerID != m_MySID  && !IsNPCSid(packet.ServerID) )
						{
							CardManager.Instance.ReserveUpdateTeamData(packet);
							break;
						}
						UpdateTeamData(packet);
                    }
                    break;
                #endregion
				#region OperationCodes.OP_TELEPORT_PAWN:
				case (byte)OperationCodes.OP_TELEPORT_PAWN:
					{
						PC_OP_TELEPORT_PAWN packet = new PC_OP_TELEPORT_PAWN(tmpPacket);
						if( !IsPawnCreated(packet.ServerID) )
							break;				
						glog.debug("TELEPORT PAWN to boardID:"+packet.BoardID+"  sid="+packet.ServerID);
						if(BoardManager.Instance.curTurnSID == packet.ServerID)
						{
							bool teleportRightNow = false;
							BoardPerson person = objectMap[packet.ServerID].GetComponent<BoardPerson>();
							if(person.moveState != BoardPerson.MoveState.WaitMoving && person.moveState != BoardPerson.MoveState.Moving)
								teleportRightNow = true;
					
							//if(BattleManager.Instance.bCombatHappened)
							//{
							//	person.ReserveTeleport_afterCombat(packet.BoardID);
								
							//}
							//else
								person.ReserveTeleport(packet.BoardID, teleportRightNow);
						}
						else
						{
							glog.debug("together teleport reserve  "+packet.ServerID);
							BoardPerson person = objectMap[BoardManager.Instance.curTurnSID].GetComponent<BoardPerson>();
							person.togetherTeleportPerson = objectMap[packet.ServerID].GetComponent<BoardPerson>();
							person.togetherTeleportPerson.ReserveTeleport(packet.BoardID, false);
						}
							
						
					}
					break;
				#endregion
				#region OperationCodes.OP_CHANGE_ABNORMAL_EFFECT:
				case (byte)OperationCodes.OP_CHANGE_ABNORMAL_EFFECT:
					{
						PC_OP_CHANGE_ABNORMAL_EFFECT packet = new PC_OP_CHANGE_ABNORMAL_EFFECT(tmpPacket);
						ProcessAbnormalEffect(packet);
					}
					break;
				#endregion
				#region OperationCodes.OP_CHOOSE_MOVE_PATH:
				case (byte)OperationCodes.OP_CHOOSE_MOVE_PATH:
					{
						PC_OP_CHOOSE_MOVE_PATH packet = new PC_OP_CHOOSE_MOVE_PATH(tmpPacket);
						if( !IsPawnCreated(packet.ServerID) )
							break;
						glog.debug("Candidate Board Count " + packet.CandidateBoardCount);
						candidatePathBoard.Clear();
						for (int i = 0; i < packet.CandidateBoardCount; i++)
						{
							glog.debug("boardID -- " + packet.BoardIDList[i]);
							candidatePathBoard.Add(packet.BoardIDList[i]);
							objectMap[packet.ServerID].GetComponent<BoardPerson>().SetWaitingSelectPath(packet.BoardIDList[i], new DateTime(packet.TimeStamp).AddTicks(-CSceneManager.TimeOffset) );
						}
					}
					break;
				#endregion
				#region OperationCodes.OP_USE_SKILL:
				case (byte)OperationCodes.OP_USE_SKILL:
					{
						PC_OP_USE_SKILL packet = new PC_OP_USE_SKILL(tmpPacket);
						if( !IsPawnCreated(packet.ServerID) )
							break;	
						glog.debug(" ------------------------------  Use Skill SID [" + packet.ServerID + "] SkillID[" + packet.SkillID + "] target="+packet.TargetID);
						ProcessUseSkill(packet.ServerID, packet.SkillID, packet.TargetID);

					}
					break;
				#endregion
				#region OperationCodes.OP_USE_TEMP_SKILL:
				case (byte)OperationCodes.OP_USE_TEMP_SKILL:
					{
						PC_OP_USE_TEMP_SKILL packet = new PC_OP_USE_TEMP_SKILL(tmpPacket);
						if( !IsPawnCreated(packet.ServerID) )
							break;
						Debug.LogError("   Use Temp Skill SID [" + packet.ServerID + "] SkillID[" + packet.TempSkillID + "]");
						ProcessUseSkill(packet.ServerID, packet.TempSkillID, packet.TargetID);

					}
					break;
				#endregion
				#region OperationCodes.OP_USE_ITEM:
				case (byte)OperationCodes.OP_USE_ITEM:
					{
						PC_OP_USE_ITEM packet = new PC_OP_USE_ITEM(tmpPacket);
						if( !IsPawnCreated(packet.ServerID) )
							break;	
						glog.debug(" ------------ Use Item SID [" + packet.ServerID + "] itemType[" + packet.ItemType + "]");
						UIManager.Instance.ShowMoveRollButton(false);
						if(packet.ItemType == (int)ItemType.HPPotion)
						{
							
							//GetBoardPerson(packet.ServerID).bUsedHPRestoreEffect = true;
						}
						if( packet.ItemType == (int)ItemType.ResurrectPotion )
						{
							HudManager.Instance.ChangeFace(packet.ServerID, true);
							EffectManager.Instance.PlayEffectParent(9, GetBoardPerson(packet.ServerID).transform );
							EffectManager.Instance.DisableParticle(9, 2.0f);
							CardManager.Instance.ShowSkillNameEffect(CStringTableManager.Instance.GetItemById(1705) );
						}
					}
					break;
				#endregion
                #region OperationCodes.SC_CREATE_TEAM_DATA:
                case (byte)OperationCodes.SC_CREATE_TEAM_DATA:
					{
                        PC_SC_CREATE_TEAM_DATA packet = new PC_SC_CREATE_TEAM_DATA(tmpPacket);
						if( !IsPawnCreated(packet.ServerID) )
							break;
						for (int i = 0; i < packet.TeamUnitCount; i++)
						{
							glog.debug("Create Team [" + packet.ServerID + "] -- Slot["+i+"] --- UnitID["+ packet.UnitIDList[i] +"]");
							bool isMySid = false;
							bool isBossSid = false;
							bool isNPC = false;

							CUnitData unitData = CUnitDataManager.Instance.GetUnitData(packet.UnitIDList[i]);
							BoardPerson person = GetBoardPerson(packet.ServerID);
							if( BoardManager.Instance.boardPersonNPCList.Contains( person) )
								isNPC = true;
							if(m_MySID == packet.ServerID)
								isMySid = true;
							if(m_BossSID == packet.ServerID)
								isBossSid = true;
							bool shouldShowCharByUnit = false;
							if( BoardManager.Instance.boardPersonNPCList.Contains( person ) || isBossSid )
								shouldShowCharByUnit = true;
							if(person.isTrapDecoy)
								shouldShowCharByUnit = false;
							if( shouldShowCharByUnit)
							{
								if(i == 0)
								{
									string modelName = unitData.model_name;
									//if(isBossSid)
									//	modelName = "b1";// for persentation 1212
									if( modelName =="")
									{
										person.char_name = "n1";
									}
									else
										person.char_name = modelName;
							
//									if(person.char_name=="e1")
//										person.char_name = "n1";
//									if(person.char_name=="e2")
//										person.char_name = "n2";
//									if(person.char_name=="e3")
//										person.char_name = "n3";		
//									if(person.char_name=="")
//										person.char_name = "n1";
							
									//for boss test
									if( CSceneManager.bTestBossAnimation && person.char_name=="n1")
										person.char_name = "b1";
									
									glog.debug("model_name="+person.char_name);
									person.InitAnimForNPC();
								}						
							}
							if(isMySid || isNPC)
								CardManager.Instance.CreateTeam(isMySid, isBossSid, isNPC, packet.ServerID, i, packet.UnitIDList[i], unitData, person.order, packet.UnitLevelList[i] );
							else
								CardManager.Instance.ReserveCreateTeam(packet.ServerID, i, packet.UnitIDList[i], packet.UnitLevelList[i] );
							//MainHUDUI.Instance.SetUnitSlot(packet.ServerID, i, packet.UnitIDList[i], CUnitDataManager.Instance.GetUnitData(packet.UnitIDList[i]) , isAICreated,nAICount);
						}
						for(int i=packet.TeamUnitCount; i< 5;i++)
						{
							//glog.debug("Deactivated unit "+i);
							//MainHUDUI.Instance.SetUnitSlot(packet.ServerID, i, 0, null , false, 0);
						}
					}
					break;
				#endregion
                #region OperationCodes.SC_ADD_TEAM_DATA:
                case (byte)OperationCodes.SC_ADD_TEAM_DATA:
					{
                        PC_SC_ADD_TEAM_DATA packet = new PC_SC_ADD_TEAM_DATA(tmpPacket);
						if( !IsPawnCreated(packet.ServerID) )
							break;				
						for (int i = 0; i < packet.ListCount; i++)
						{
							glog.debug("*** Add Team [" + packet.ServerID + "] -- Slot["+packet.SlotList[i]+"] --- UnitID["+ packet.UnitIDList[i] +"]  level="+packet.UnitLevelList[i]);
							CardManager.Instance.AddTeam(packet.ServerID, packet.SlotList[i], packet.UnitIDList[i], CUnitDataManager.Instance.GetUnitData(packet.UnitIDList[i]), packet.UnitLevelList[i] );
							//MainHUDUI.Instance.SetUnitSlot(packet.ServerID, i, packet.UnitIDList[i], CUnitDataManager.Instance.GetUnitData(packet.UnitIDList[i]) , isAICreated,nAICount);
						}
					}
					break;
				#endregion				
				#region OperationCodes.OP_DELETE_PAWN_FROM_GAME:
				case (byte)OperationCodes.OP_DELETE_PAWN_FROM_GAME:
					{
						PC_OP_DELETE_PAWN_FROM_GAME packet = new PC_OP_DELETE_PAWN_FROM_GAME(tmpPacket);
				
						glog.debug("DELETE PAWN [" + packet.ServerID + "]");
						//BoardManager.Instance.toBeDeletedPawnID = packet.ServerID;
						GetBoardPerson(packet.ServerID).DeletePawn();
					}
					break;
				#endregion
				#region OperationCodes.OP_GOT_INSTANT_EFFECT:
				case (byte)OperationCodes.OP_GOT_INSTANT_EFFECT:
					{
						PC_OP_GOT_INSTANT_EFFECT packet = new PC_OP_GOT_INSTANT_EFFECT(tmpPacket);

						if (packet.InstantType == (int)InstantType.RESURRECT)
						{
							glog.debug("Resurrect");
						}
						
					}
					break;
				#endregion
				#region OperationCodes.OP_TEMP_BOX:
				case (byte)OperationCodes.OP_TEMP_BOX:
					{
						PC_OP_TEMP_BOX packet = new PC_OP_TEMP_BOX(tmpPacket);
						if( !IsPawnCreated(packet.ServerID) )
							break;
						
						TempBoxAction boxAction = (TempBoxAction)packet.TempBoxAction;
						Debug.LogError(packet.ServerID+" OP_TEMP_BOX: "+boxAction);
						if (boxAction==TempBoxAction.GET_FROM_STOP_BOARD || boxAction==TempBoxAction.GET_FROM_NPC || boxAction==TempBoxAction.GET_FROM_PASS_BOARD || boxAction==TempBoxAction.GET_FROM_BONUS)
						{	
							bool bGetFromNPC = false;
							bool bGetFromNPC_bonus = false;
							bool bGetByPassingBoard = false;
							if(packet.TempBoxAction == (int)TempBoxAction.GET_FROM_NPC)
								bGetFromNPC = true;
							if(packet.TempBoxAction == (int)TempBoxAction.GET_FROM_BONUS)
							{
								glog.debug(" "+(BoxCategory)packet.BoxCategory+"  "+packet.BoxId+"  "+packet.Amount+"  "+packet.BoardID);
						        bGetFromNPC_bonus = true;
							}
							if(packet.TempBoxAction == (int)TempBoxAction.GET_FROM_PASS_BOARD)
								bGetByPassingBoard = true;
							if (packet.BoxCategory == (int)BoxCategory.ITEM || packet.BoxCategory == (int)BoxCategory.COIN)
							{
								glog.debug("Get OP_TEMP_BOX item "+packet.BoxId+"  bid="+packet.BoardID);
								if(packet.BoxId==0)
									Debug.LogError("boxID zero");
								else
								{
									CItemData itemData = CItemDataManager.Instance.GetItemData(packet.BoxId);
									if(itemData==null)
										Debug.LogError("item data null for boxID:"+packet.BoxId);
									else
										GetBoardPerson(packet.ServerID).ShowItemGetEffect(false, itemData.name, packet.Amount, bGetFromNPC, bGetByPassingBoard, packet.BoardID, bGetFromNPC_bonus);
								}
							}
							else if (packet.BoxCategory == (int)BoxCategory.UNIT)
							{
								GetBoardPerson(packet.ServerID).ShowItemGetEffect(true,"unit", packet.Amount, bGetFromNPC, bGetByPassingBoard, packet.BoardID, bGetFromNPC_bonus);
							}
						}   
					}
					break;
				#endregion
				#region OperationCodes.OP_CHANGE_BOARD_STATUS:
				case (byte)OperationCodes.OP_CHANGE_BOARD_STATUS:
					{
						PC_OP_CHANGE_BOARD_STATUS packet = new PC_OP_CHANGE_BOARD_STATUS(tmpPacket);
						ChangeBoardReason changeReason = (ChangeBoardReason)packet.ChangeReason;
						BoardInfo.TileName btNameChange = (BoardInfo.TileName)packet.BoardDataType;
						glog.debug("sid="+packet.ServerID+" OP_CHANGE_BOARD_STATUS ID[" + packet.BoardID + "] height[" + packet.Height + "] boardType[" +btNameChange + "]  "+ changeReason);
						if(packet.ServerID == 0)
							BoardManager.Instance.ChangeBoardStatus(packet.BoardID, packet.Height, packet.BoardDataType, null, changeReason);
						else
						{
							if( !IsPawnCreated(packet.ServerID) )
								break;					
							BoardPerson personToMove = objectMap[packet.ServerID].GetComponent<BoardPerson>();
							if(personToMove.IsMovingOrWaitMoving()  )
								personToMove.SetToChangeBoardStatus(packet.BoardID, packet.Height, packet.BoardDataType, changeReason);
							else
							{
								BoardManager.Instance.ChangeBoardStatus(packet.BoardID, packet.Height, packet.BoardDataType, personToMove, changeReason);	
							}
						}
						
							
					}
					break;
				#endregion
				#region OperationCodes.OP_UPDATE_ITEM_COUNT:
				case (byte)OperationCodes.OP_UPDATE_ITEM_COUNT:
					{
						PC_OP_UPDATE_ITEM_COUNT packet = new PC_OP_UPDATE_ITEM_COUNT(tmpPacket);
						glog.debug("OP_UPDATE_ITEM_COUNT hp="+packet.HPPotion+"  resr="+packet.RessurectPotion);
						MyInfo.Instance.HPPotion = packet.HPPotion;
						MyInfo.Instance.ResurrectPotion = packet.RessurectPotion;
						UIManager.Instance.SetHealItemCount(packet.HPPotion, packet.RessurectPotion);
					}
					break;
				#endregion
				#region OperationCodes.OP_SYNC_BOARD_STATUS:
				case (byte)OperationCodes.OP_SYNC_BOARD_STATUS:
					{
						PC_OP_SYNC_BOARD_STATUS packet = new PC_OP_SYNC_BOARD_STATUS(tmpPacket);
						glog.debug("Count Sync Board -- " + packet.BoardCount);
						for(int i=0; i< packet.BoardCount; i++)
						{
							int boardID = packet.BoardIDList[i];
							int height = packet.HeightList[i];
							int boardDataType = packet.BoardDataTypeList[i];
							glog.debug("bid="+boardID+"  height="+height+"  bdtype="+boardDataType);
							PathManager.Instance.GetBoardTile(boardID).SyncBoard(height, boardDataType);
						}
					
					}
					break;
				#endregion
				#region OperationCodes.OP_TURN_ALRAM:
				case (byte)OperationCodes.OP_TURN_ALRAM:
					{
						PC_OP_TURN_ALRAM packet = new PC_OP_TURN_ALRAM(tmpPacket);
						if( !IsPawnCreated(packet.ServerID) )
							break;				
						if(!isGameOrdered)
						{
							Debug.LogError("turn alram too early. return");
							break;
						}
						BoardPerson person = GetBoardPerson(packet.ServerID);
						if(packet.TurnType == (byte)TurnType.Continue)
						{
							glog.debug(packet.ServerID+"************** ContinuPlay  Turn -- " + packet.Turn + " //////// type -- " + packet.TurnType);
							CardManager.Instance.ClearReserveTeamData();
							bContinueTurnStarted = true;
							BoardManager.Instance.curTurnSID = packet.ServerID;
							BoardManager.Instance.bShowDiceNumCompleted = true;
							BoardManager.Instance.isShowDiceUIDone = true;
							if(person.isMe)
								m_isMyTurn = true;
							else
								m_isMyTurn = false;
							m_curTurn = packet.Turn;
							camControl.SetCameraFocus(person.transform);
							person.MyTurnAlarm(packet.Turn);
							HudManager.Instance.StopOtherTurnAlarm(packet.ServerID);
							break;
						}
						if(CSceneManager.isReplay && bPathRun)
						{
							FindPathToGoal();
							break;
						}
						if(person.bContinueFromRetire)
						{
							person.bContinueFromRetire = false;
							person.SetRetire( false);
						}
						if(BoardManager.Instance.curTurnSID!=0)
							GetBoardPerson(BoardManager.Instance.curTurnSID).ShowDestMark(false);
						if(!bTurnStarted)
							CardManager.Instance.ClearReserveTeamData();
						bTurnStarted = true;
						BoardManager.Instance.nCountShowUIRollMoveDice = 0;
						BoardManager.Instance.curTurnSID = packet.ServerID;
						BattleManager.Instance.ClearBattle();
						if(person.isMe)
							m_isMyTurn = true;
						else
							m_isMyTurn = false;
						
						
						
						if( !person.isRetired) {
							if(m_isMyTurn)
								SoundManager.Instance.PlaySound(ESound.MyTurn_Dice);
							BoardManager.Instance.nextTurnOK = false;
							camControl.SetCameraFocus(person.transform);
							person.isBackExpelled=false;
							person.battleOpponent = null;
							glog.debug(packet.ServerID+"**************  Turn -- " + packet.Turn + " //////// type -- " + packet.TurnType, LOGCOLOR.BLUE);
							m_curTurn = packet.Turn;
							BoardManager.Instance.ActivateDiceOverHead(person, DiceShapeType.Normal);
							person.MyTurnAlarm(packet.Turn);
							HudManager.Instance.StopOtherTurnAlarm(packet.ServerID);
							
							BoardManager.Instance.CheckNextTurnOK();
						}
						//else
						//	BoardManager.Instance.nextTurnOK = true;
						
						if(CSceneManager.isReplay && bPauseAtTurn)
						{
							if(packet.Turn == pauseTurn)
								Debug.Break();
						}						
					}
					break;
				#endregion
				#region OperationCodes.OP_REWARD_LIST:
				case (byte)OperationCodes.OP_REWARD_LIST:
					{
						PC_OP_REWARD_LIST packet = new PC_OP_REWARD_LIST(tmpPacket);
						glog.debug("OP_REWARD_LIST "+packet.BoxCount+"  exp="+packet.Exp+"  maxReward="+packet.SelectCount);
						// exp는 0이다  
						///packet.SelectedCategoryList 
						//BoxCategory.NONE
						bool isPvpRoom = true;
						if(packet.RoomType==1)
							isPvpRoom = false;
						UIManager.Instance.InitReward(isPvpRoom);
						for(int i=0; i< packet.BoxCount; i++)
						{
							BoxCategory cat = (BoxCategory)(packet.BoxCategoryList[i]);
							glog.debug("category="+cat  +"  id="+packet.BoxIdList[i]+"  count="+packet.BoxCountList[i]);
							UIManager.Instance.AddRewardItem( packet.BoxCategoryList[i], packet.BoxIdList[i], packet.BoxCountList[i]);
						}
				
						//UIManager.Instance.InitReward();
						for(int i=0; i< packet.SelectCount; i++)
						{
							UIManager.Instance.AddSelectedReward ( packet.SelectedCategoryList[i]   );
						}
					}
					break;
				#endregion
				#region OperationCodes.OP_COMBAT_INFO:
				case (byte)OperationCodes.OP_COMBAT_INFO:
					{
						PC_OP_COMBAT_INFO packet = new PC_OP_COMBAT_INFO(tmpPacket);
						glog.debug("OP_COMBAT_INFO bid="+packet.BoardID+"  attacker="+packet.Attacker+"  defender="+packet.Defender); 
						combatInfo_attackerSID = packet.Attacker;
						combatInfo_defenderSID = packet.Defender;
						BattleManager.Instance.SetMaxCombatCount(0);
						BattleManager.Instance.combatCount = 0;
						if( BoardManager.Instance.curTurnSID == packet.Attacker)
							GetBoardPerson(BoardManager.Instance.curTurnSID).SetCombatInfo( GetBoardPerson(packet.Defender) );
						else if( BoardManager.Instance.curTurnSID == packet.Defender)
							GetBoardPerson(BoardManager.Instance.curTurnSID).SetCombatInfo( GetBoardPerson(packet.Attacker) );
					}
					break;
				#endregion		
				#region OperationCodes.OP_RETIRE:
				case (byte)OperationCodes.OP_RETIRE:
					{
						PC_OP_RETIRE packet = new PC_OP_RETIRE(tmpPacket);
						glog.debug("************ OP_RETIRE SID=" + packet.ServerID + "  BID=" + packet.BoardID);
						GetBoardPerson(packet.ServerID).SetRetire( true);
					}
					break;
				#endregion							
				#region OperationCodes.OP_UNIT_ACTIVATION_INFO:
				case (byte)OperationCodes.OP_UNIT_ACTIVATION_INFO:
					{
						PC_OP_UNIT_ACTIVATION_INFO packet = new PC_OP_UNIT_ACTIVATION_INFO(tmpPacket);
						glog.debug("************ OP_UNIT_ACTIVATION_INFO SID=" + packet.ServerID);
						UnitActivationReason reason = (UnitActivationReason)packet.Reason;
						glog.debug("info  "+packet.ActiveQueueCount+"  "+packet.DeactiveCount +"  activeSlot="+packet.ActiveSlot+"   "+reason);
						//if( IsNPCSid(packet.ServerID) )
						//	break;
						if(!bTurnStarted && !bContinueTurnStarted && packet.ServerID != m_MySID && !IsNPCSid(packet.ServerID) )
						{
							CardManager.Instance.ReserveUnitActivationInfo(packet);
							break;
						}
						UpdateUnitActivationInfo(packet);
					}
					break;
				#endregion	
                #region OperationCodes.SC_SYNC_SKILL_CONDITION:
                case (byte)OperationCodes.SC_SYNC_SKILL_CONDITION:
					{
                        PC_SC_SYNC_SKILL_CONDITION packet = new PC_SC_SYNC_SKILL_CONDITION(tmpPacket);
				
						glog.debug("************ OP_SYNC_SKILL_CONDITION SID=" + packet.ServerID);
						glog.debug("************ OP_SYNC_SKILL_CONDITION skill_1st=" + packet.Skill_1st_Launch.ToString());
						glog.debug("************ OP_SYNC_SKILL_CONDITION skill_2nd=" + packet.Skill_2nd_Launch.ToString());
						glog.debug("************ OP_SYNC_SKILL_CONDITION skill_3rd=" + packet.Skill_3rd_Launch.ToString());
						glog.debug("************ OP_SYNC_SKILL_CONDITION skill_4th=" + packet.Skill_4th_Launch.ToString());
						UIManager.Instance.SetSkillCastableCondition( packet.Skill_1st_Launch, packet.Skill_2nd_Launch, packet.Skill_3rd_Launch, packet.Skill_4th_Launch);
						for(int i=0; i< packet.TempSkillCount; i++)
							UIManager.Instance.SetTempSkillCastableCondition(i, packet.TempSkillSlotLaunchList[i]);
						UIManager.Instance.SetSkillAndItem();
					}
					break;
				#endregion
				#region OperationCodes.SC_SYNC_TEMP_SKILL:
				case (byte)OperationCodes.SC_SYNC_TEMP_SKILL:
					{
						PC_SC_SYNC_TEMP_SKILL packet = new PC_SC_SYNC_TEMP_SKILL(tmpPacket);
						if(packet.ServerID!= m_MySID)
							break;
						Debug.LogError("************ SC_SYNC_TEMP_SKILL SID=" + packet.ServerID+"  skillcount="+packet.SkillCount);
						for(int i=0; i< packet.SkillCount; i++)
						{
							glog.debug("skill id = "+packet.SkillIdList[i]);
							UIManager.Instance.SetTempSkill(i, packet.SkillIdList[i]);
						}
					}
					break;
				#endregion
				#region OperationCodes.SC_SYSTEM_MSG:
                case (byte)OperationCodes.SC_SYSTEM_MSG:
					{
                        PC_SC_SYSTEM_MSG packet = new PC_SC_SYSTEM_MSG(tmpPacket);
						glog.debug("************ PC_OP_SYSTEM_MSG SID=" + packet.ServerID);
						glog.debug("************ PC_OP_SYSTEM_MSG MsgID=" + packet.MsgID);
						glog.debug("************ PC_OP_SYSTEM_MSG String=" + CStringTableManager.Instance.GetItemById(packet.MsgID));
						//UIManager.Instance.ShowSkillInfo( CStringTableManager.Instance.GetItemById(packet.MsgID) );
					}
					break;
				#endregion		
				#region OperationCodes.OP_CHECK_CLIENT_LOADING:
				case (byte)OperationCodes.OP_CHECK_CLIENT_LOADING:
					{
						PC_OP_CHECK_CLIENT_LOADING packet = new PC_OP_CHECK_CLIENT_LOADING(tmpPacket);
						glog.debug("************ PC_OP_CHECK_CLIENT_LOADING SID=" + packet.ServerID);

						if (objectMap[packet.ServerID].GetComponent<BoardPerson>().isMe)
						{
							CNetworkManager.Instance.SendPacket(packet);
						}
					}
					break;
				#endregion		
                #region OperationCodes.SC_ROLL_DIRECTION_DICE_RESULT:
                case (byte)OperationCodes.SC_ROLL_DIRECTION_DICE_RESULT:
                    {
						// direction roll
                        PC_SC_ROLL_DIRECTION_DICE_RESULT packet = new PC_SC_ROLL_DIRECTION_DICE_RESULT(tmpPacket);
                        glog.debug("************ PC_OP_ROLL_DIRECTION_DICE_RESULT SID=" + packet.ServerID);
                        glog.debug("value -- " + packet.Value + "  next -- " + packet.NextBoardID);
						BoardManager.Instance.WaitForDirectionRoll(packet.ServerID, packet.Value, packet.NextBoardID);

                        if (!GetBoardPerson(packet.ServerID).isMe)
                        {
                            // 희소 상대편 시간컨트롤
							HudManager.Instance.StopGageAni(packet.ServerID);
                        }
                    }
                    break;
                #endregion
                #region OperationCodes.SC_SHOW_RANDOM_BOX:
                case (byte)OperationCodes.SC_SHOW_RANDOM_BOX:
                    {
                        PC_SC_SHOW_RANDOM_BOX packet = new PC_SC_SHOW_RANDOM_BOX(tmpPacket);
                        /* TODO */
                        if (packet.ServerID == BoardManager.Instance.boardPerson_me.SID)
                        {
                            glog.debug(String.Format("Max[{0}] Select[{1}] TimeStamp[{2}]", packet.BoxCount, packet.SelectCount, packet.TimeStamp));

                            if (packet.SelectCount == 0)
                            {
                                SendLeave();
                            }
                            else
                            {
								UIManager.Instance.ShowSelectRandomBoxWindow(packet.BoxCategoryList, packet.BoxIdList, packet.AmountList, packet.BoxCount, packet.SelectCount);
                            }
                        }
                    }
                    break;
                #endregion
                #region OperationCodes.SC_ROLL_COMBAT_DICE_RESULT:
                case (byte)OperationCodes.SC_ROLL_COMBAT_DICE_RESULT:
                    {
                        PC_SC_ROLL_COMBAT_DICE_RESULT packet = new PC_SC_ROLL_COMBAT_DICE_RESULT(tmpPacket);
						UIType combatDiceType = (UIType)packet.DiceType;
						glog.debug(String.Format(packet.ServerID+" combatDice result Type[{0}] Count[{1}]", combatDiceType, packet.RollDiceCount));
						UIManager.Instance.ClearBattleRoll();
						bool isAttackerDiceResult = false;
						if(combatDiceType == UIType.UI_ROLL_ATTACK_DICE)
							isAttackerDiceResult = true;
						byte [] nDiceList = new byte[packet.RollDiceCount];
                        for (int i = 0; i < packet.RollDiceCount; i++)
                        {
                            glog.debug(String.Format("value[{0}]",packet.RollValueList[i]));
							nDiceList[i] = packet.RollValueList[i];
                        }

						if(!bTurnStarted && !GetBoardPerson(packet.ServerID).IsMovingOrWaitMoving())
						{
							if(!BattleManager.Instance.isRedice && !BattleManager.Instance.isRematch)
							{
								BoardManager.Instance.bWaitForUIBattleDice = true;
								if(GetBoardPerson(packet.ServerID).isWaitingBattleDiceList)
								{
									battleDiceList = new byte[packet.RollDiceCount];
									for (int i = 0; i < packet.RollDiceCount; i++)
										battleDiceList[i] = packet.RollValueList[i];
								}
								else
									GetBoardPerson(packet.ServerID).ContunueBattle( nDiceList, isAttackerDiceResult);
								break;
							}
						}

						if(packet.ServerID == rollCombatDiceSID )
						{
							glog.debug("1");
							BoardManager.Instance.ShowDiceUIBattle( GetBoardPerson(packet.ServerID), nDiceList, null, isAttackerDiceResult);
							//if(packet.ServerID==combatInfo_attackerSID)
							//	BoardManager.Instance.ShowDiceUIBattle( GetBoardPerson(packet.ServerID), nDiceList, null, true);
							//else
							//	BoardManager.Instance.ShowDiceUIBattle( GetBoardPerson(packet.ServerID), nDiceList, null, false);
						}
						else if(packet.ServerID == battleAIThinkingSID)
						{
							if(bAIBattleDiceRollImmediately)
							{
								glog.debug("2");
								BoardManager.Instance.ShowDiceUIBattle( GetBoardPerson(packet.ServerID), nDiceList, null, isAttackerDiceResult);
								//if(packet.ServerID==combatInfo_attackerSID)
								//	BoardManager.Instance.ShowDiceUIBattle( GetBoardPerson(packet.ServerID), nDiceList, null, true);
								//else
								//	BoardManager.Instance.ShowDiceUIBattle( GetBoardPerson(packet.ServerID), nDiceList, null, false);
							}
							else
							{
								glog.debug("3");
								battleDiceList = new byte[packet.RollDiceCount];
								for (int i = 0; i < packet.RollDiceCount; i++)
									battleDiceList[i] = packet.RollValueList[i];
							}
						}


                        if (!GetBoardPerson(packet.ServerID).isMe)
                        {
                            // 희소 상대편 시간컨트롤
							HudManager.Instance.StopGageAni(packet.ServerID);
                        }

                        //if (packet.DiceType == (byte)UIType.UI_ROLL_ATTACK_DICE)
                        //{
                            /* 공격 주사위 결과 */
                        //}
						//else if (packet.DiceType == (byte)UIType.UI_ROLL_DEFENCE_DICE)
                        //{
                            /* 방어 주사위 결과 */
                       // }
                    }
                    break;
                #endregion
                #region OperationCodes.SC_STAGE_DATA:
                case (byte)OperationCodes.SC_STAGE_DATA:
				{
					PC_SC_STAGE_DATA packet = new PC_SC_STAGE_DATA(tmpPacket);
					glog.debug("***** SC_STAGE_DATA runnerCount="+packet.RunnerCnt);
					BoardManager.Instance.runnerCnt = packet.RunnerCnt;
				}
					break;
				#endregion
                #region OperationCodes.SC_ORDER_CARD:
                case (byte)OperationCodes.SC_ORDER_CARD:
                    {
						bool isMe = false;
                        PC_SC_ORDER_CARD packet = new PC_SC_ORDER_CARD(tmpPacket);
                        glog.debug("***** SC_ORDER_CARD runnerCount=" + packet.CardCount);

						if( UIManager.Instance.chooseGameOrderWindow == null )
							UIManager.Instance.ShowChooseGameOrderWindow();

						for(int i=0; i<packet.CardCount; i++)
						{
							if( packet.SelectUserIDList[i] > 0 )
							{
								if( packet.SelectUserIDList[i] == BoardManager.Instance.boardPerson_me.SID)
								{
									isMe = true;
									UIManager.Instance.chooseGameOrderWindow.SetMySelectedCardState();
								}
								else
									UIManager.Instance.chooseGameOrderWindow.DisableOtherCard(i);
							}
						}

						if( !isMe )
							UIManager.Instance.chooseGameOrderWindow.ResetChooseStatus();

//                        PC_CS_SELECT_ORDER_CARD sentPacket = new PC_CS_SELECT_ORDER_CARD();
//                        sentPacket.ServerID = BoardManager.Instance.boardPerson_me.SID;
//                        sentPacket.Index = 0;
//
//                        CNetworkManager.Instance.SendPacket(sentPacket);
                    }
                    break;
                #endregion
                #region OperationCodes.SC_ORDER_CARD_RESULT:
                case (byte)OperationCodes.SC_ORDER_CARD_RESULT:
                    {
                        PC_SC_ORDER_CARD_RESULT packet = new PC_SC_ORDER_CARD_RESULT(tmpPacket);
                        glog.debug("***** SC_ORDER_CARD_RESULT runnerCount=" + packet.CardCount);
	
						for(int i=0; i<packet.CardCount; i++)
						{
							if (packet.SelectUserIDList[i] == BoardManager.Instance.boardPerson_me.SID)
							{
								Debug.LogError(i + " :: It's me!!"); 
								UIManager.Instance.chooseGameOrderWindow.orderCardObjects[i].GetComponent<GameOrderCard>().isMe = true;
								UIManager.Instance.chooseGameOrderWindow.orderCardObjects[i].GetComponent<GameOrderCard>().myTempSkillId = packet.TempSkillIDList[i];
							}
						}
						UIManager.Instance.chooseGameOrderWindow.FlipFirstOrderCard(packet.ResultList);
                    }
                    break;
                #endregion
                default:
					if(CSceneManager.isReplay)
						ProcessForcePacketQueue(tmpPacket);
					else
						glog.debug("Unknown Packet Recieved [" + (OperationCodes)tmpPacket[0] +"]");
                    break;
            }
        }

		if(Input.GetKeyDown(KeyCode.P) )
			Debug.Break();
	}
	
	static bool IsPawnCreated(int sid)
	{
		if( objectMap.ContainsKey(sid))
			return true;
		return false;
	}
	
	public static BoardPerson GetBoardPerson(int sid)
	{
		if(objectMap.ContainsKey(sid) )
			return objectMap[sid].GetComponent<BoardPerson>();
		else
			return null;
	}
	
	static bool EventHandlerForStageManagerWrapper(DICE_GS.LogType type, string msg)
	{
		if (CNetworkManager.Instance.Connected)
        {
            glog.debug("msg From Network :" + msg);
        }
        else
        {
            glog.debug("Msg From DLL :" + msg);
        }
		
		msgQueue.Enqueue(msg);
		return false;
	}

    public static bool PacketHandler(Dictionary<byte, object> _packet)
    {
        if (packetQueue != null)
        {
			byte packet_code = (byte) _packet[0];
			packetTakenList.Add(packet_code);
			if( IsForcePacket(packet_code) )
				ForcePacketQueue.Enqueue(_packet);
			else
            	packetQueue.Enqueue(_packet);
			packetReplayInfo.Enqueue( new PacketReplayInfo(Time.timeSinceLevelLoad, _packet) );
			//if(manager.bShowPacketLog)
			//{
				WriteToRuntimeLog(packet_code);
			//}
        }
        else
        {
            glog.debug("Missed packet[" + _packet[0] + "]");

        }
        return false;
    }

	public static void WriteToRuntimeLog(byte packet_code)
	{
		OperationCodes opcode = (OperationCodes)packet_code;
		strLog = String.Format("{0}", opcode);
		if(opcode== OperationCodes.OP_TURN_ALRAM)
			RuntimeLog.LogCustom(strLog, Color.cyan);
		else if(opcode== OperationCodes.OP_COMBAT_RESULT)
			RuntimeLog.LogCustom(strLog, Color.green);
		else if(opcode== OperationCodes.OP_MOVE_BACKWARD)
			RuntimeLog.LogCustom(strLog, Color.yellow);
		else
			RuntimeLog.Log(strLog);
	}

    static bool PrintLog(string msg)
    {
#if UNITY_EDITOR
        glog.debug("Log:" + msg);
#endif
        return true;
    }

    public static void MakeAIRunner()
    {
		if (CNetworkManager.Instance.Connected)
        {
            //CNetworkManager.Instance.SendRequest("MakeAI");
			if(nPawnCreated>=4)
				return;
			
			glog.debug("MakeAIRunner");
            PC_CS_CREATE_PAWN packet = new PC_CS_CREATE_PAWN();
            packet.PawnType = (byte)GAME_PAWN_TYPE.AI;

            //CNetworkManager.Instance.SendPacket(packet.Protocol, packet.GetParam());
			CNetworkManager.Instance.SendPacket(packet);
		
        }
    }
	
	public static bool IsPCType(int pawnType)
	{
		if (pawnType == (int)GAME_PAWN_TYPE.PC || pawnType == (int)GAME_PAWN_TYPE.BOT)
			return true;
		return false;
	}

    public static bool IsNPCType(int pawnType)
    {
        if (pawnType == (int)GAME_PAWN_TYPE.NPC_BOSS || pawnType == (int)GAME_PAWN_TYPE.NPC_MINION)
            return true;

        return false;
    }

	public static CPawn CreateNewPawn(int _SID, GAME_PAWN_TYPE _type, int _pawn, int _StartBoard, int _MasterUnitID, int nMasterUnitLevel, int nDiceID, int PathID)
	{
        if (CSceneManager.isReplay)
            return new CPawn(_SID, _type, _pawn, Instance, _MasterUnitID, nMasterUnitLevel, nDiceID, PathID);
        else
        {
            return Instance.CreateNewPawn(_SID, _type, _pawn, _StartBoard, _MasterUnitID, nMasterUnitLevel, nDiceID, PathID);
        }
	}
	
	public static int GetAICharSelectNum()
	{
		List<int> numList = new List<int>();
		for(int i=1; i<=4; i++)
		{
			if(i!=MyInfo.Instance.pawnId)
				numList.Add(i);
		}
		if(aiCharSelectNum>=numList.Count)
			return 1;
		return numList[aiCharSelectNum++];
	}

	public static bool IsNPCSid(int sid)
	{
		if(NPCIdList.Contains(sid) )
			return true;
		return false;
	}
	
    public static void CreateNewRunner(PC_SC_CREATE_PAWN packet)
	{
//		if( BoardManager.Instance.isBoardPersonMoving || BoardManager.Instance.isWaitingForBoardPersonMoving)
//		{
//			if( IsNPCType(packet.PawnType) )
//			{
//				reserveCreatePawnPacket = packet;
//				return;
//			}
//		}

		int _SID = packet.ServerID;
		if(_SID==0)
		{
			Debug.LogError("CreateNewRunner sid=0 ");
			return;
		}
		int _MasterUnitID = packet.MasterUnitID;
		int _startBoard = packet.CurrentBoard;
		int pawn = packet.Pawn;
		int pawnType = packet.PawnType;
		bool isMe = packet.IsMaster;
		string nickName = packet.Nickname;
		int nMasterUnitLevel = packet.MasterUnitLevel;
		int charPawn = packet.Pawn;
		int pathID = packet.PathID;
		bool bIsRetire = packet.IsRetire;
        int nDiceID = packet.DiceID;
        int nLevel = packet.PlayerLevel;
		int presetId = packet.PresetID;

		if (IsPCType(pawnType))
		{}
        else if (pawnType == (int)GAME_PAWN_TYPE.AI || pawnType == (int)GAME_PAWN_TYPE.BOSS)
			isMe = false;
		else if (IsNPCType(pawnType))	
		{
			isMe = false;		
			NPCIdList.Add(_SID);
		}
		
		if(isMe) {
			BoardManager.Instance.mySID = _SID;
		}
		
        //Vector3 newPos = PathManager.Instance.GetBoardTile(_startBoard).transform.position;		
       // newPos.y += BoardManager.Instance.upOffset;
		
		GameObject go = null;
		isAICreated = false;
		nPawnCreated++;
		if (IsPCType(pawnType))
        	go = Instantiate(BoardManager.Instance.boardPersonPlayerPrefab) as GameObject;
		else if(pawnType == (int)GAME_PAWN_TYPE.AI || pawnType == (int)GAME_PAWN_TYPE.BOSS)
		{
			go = Instantiate(BoardManager.Instance.boardPersonPlayerPrefab) as GameObject;
//			if(nAICount==0)
//				go.GetComponent<tk2dSprite>().color = new Color( 150/255.0f, 1 , 1, 1);
//			else if(nAICount==1)
//				go.GetComponent<tk2dSprite>().color = new Color( 1, 150/255.0f , 1, 1);
//			else if(nAICount==2)
//				go.GetComponent<tk2dSprite>().color = new Color( 1, 1 , 150/255.0f, 1);
			nAICount++;
			isAICreated = true;
		}
		else if(IsNPCType(pawnType))
		{
			go = Instantiate(BoardManager.Instance.boardPersonPlayerPrefab) as GameObject;
			//go.GetComponent<tk2dSprite>().color = new Color( 75/255.0f, 75/255.0f , 75/255.0f, 1);
		}

		//createpawn_zoffset += 0.001f;
        //newPos.z = go.transform.position.z + createpawn_zoffset;
        //go.transform.position = newPos;
		BoardPerson thisPerson = go.GetComponent<BoardPerson>();
		thisPerson.shadow = Instantiate(BoardManager.Instance.playerShadowPrefab) as GameObject;
		
		thisPerson.mypath = pathID;

		//For AIEmotion Chat
		//Add by Hyunseung(2014.2.24)
		if( pawnType == (int)GAME_PAWN_TYPE.AI)
			thisPerson.AIPresetId = presetId;
		
		//if(nPawnCreated % 2 ==0)
		//	thisPerson.char_name = "02";
		//else
		//	thisPerson.char_name = "02";
		glog.debug(_SID + "  charPawn = "+charPawn);
		if(charPawn==0)
			charPawn = 2;
		thisPerson.charID = charPawn;
		if(CSceneManager.manager.testCharID>0 && isMe)
			thisPerson.charID = CSceneManager.manager.testCharID;
		//if(CSceneManager.charSelected==6)
		//	thisPerson.charID=6;
		
		//if(pawnType == (int)GAME_PAWN_TYPE.AI)
		//	thisPerson.charID = GetAICharSelectNum();
		
		if(pawnType == (int)GAME_PAWN_TYPE.BOSS)
			thisPerson.charID = 1;
		
		bool isTrapDecoy = false;
		if(BoardManager.Instance.bUsedTrapDecoy)
		{
			BoardManager.Instance.bUsedTrapDecoy = false;
			isTrapDecoy = true;
		}		
		thisPerson.isTrapDecoy = isTrapDecoy;

        if (pawnType != (int)GAME_PAWN_TYPE.BOSS && !IsNPCType(pawnType) || isTrapDecoy)
		{
			thisPerson.InitAnimation(0);
			thisPerson.SetInitialCurrentBoard(PathManager.Instance.GetBoardTile(_startBoard), true, totalPlayerCount+1);
		}
		else
			thisPerson.SetInitialCurrentBoard(PathManager.Instance.GetBoardTile(_startBoard), false, totalPlayerCount+1);

        if (!IsNPCType(pawnType))
        	Camera.main.gameObject.GetComponent<CameraControl>().SetCameraFocus(go.transform);

		go.AddComponent("CPawnWrapper");
		CPawnWrapper pw = go.GetComponent<CPawnWrapper>();
		
		if (IsPCType(pawnType))
		{
            pw.Instance = CreateNewPawn(_SID, (GAME_PAWN_TYPE)pawnType, pawn, _startBoard, _MasterUnitID, nMasterUnitLevel, nDiceID, pathID);
			thisPerson.pawnType = (GAME_PAWN_TYPE)pawnType;
			CardManager.Instance.CreateDeck(_SID);
		}
		else if(pawnType == (int)GAME_PAWN_TYPE.AI)
		{
            pw.Instance = CreateNewPawn(_SID, GAME_PAWN_TYPE.AI, pawn, _startBoard, _MasterUnitID, nMasterUnitLevel, nDiceID, pathID);
			thisPerson.pawnType = GAME_PAWN_TYPE.AI;
			CardManager.Instance.CreateDeck(_SID);
			
		}
		else if(pawnType == (int)GAME_PAWN_TYPE.BOSS)
		{
            pw.Instance = CreateNewPawn(_SID, GAME_PAWN_TYPE.BOSS, pawn, _startBoard, _MasterUnitID, nMasterUnitLevel, nDiceID, pathID);
			thisPerson.pawnType = GAME_PAWN_TYPE.BOSS;
			CardManager.Instance.CreateDeck(_SID);
			
		}
		else if(pawnType == (int)GAME_PAWN_TYPE.NPC_MINION)
		{
            pw.Instance = CreateNewPawn(_SID, GAME_PAWN_TYPE.NPC_MINION, pawn, _startBoard, _MasterUnitID, nMasterUnitLevel, nDiceID, pathID);
            thisPerson.pawnType = GAME_PAWN_TYPE.NPC_MINION;
			CardManager.Instance.CreateDeck(_SID);
		}
        else if (pawnType == (int)GAME_PAWN_TYPE.NPC_BOSS)
        {
            pw.Instance = CreateNewPawn(_SID, GAME_PAWN_TYPE.NPC_BOSS, pawn, _startBoard, _MasterUnitID, nMasterUnitLevel, nDiceID, pathID);
            thisPerson.pawnType = GAME_PAWN_TYPE.NPC_BOSS;
            CardManager.Instance.CreateDeck(_SID);
        }

		//testcode
		if (pawnType == (int)GAME_PAWN_TYPE.BOT)
		{
			CSceneManager.BOTIsOn = true;
		}

		if(pw.Instance==null)
			glog.debug("pw.instance null");

		if(pw.Instance.SID > 0)
		{
			if (nickName.Equals(""))
			{
				pw.Instance.Nickname = "Runner_" + _SID;
			}
			else
			{
				pw.Instance.Nickname = nickName;
			}

            pw.Instance.Level = nLevel;

            go.name = "Runner_" + _SID;
            if (IsNPCType(pawnType))
				go.name = "NPC_" + _SID;
			
			thisPerson.SID = pw.Instance.SID;
			thisPerson.isMe = isMe;
			thisPerson.nickName = pw.Instance.Nickname;
			thisPerson.nLevel = nLevel;
            if (isMe)
            {
                m_MySID = pw.Instance.SID;
            }
			
			glog.debug (" Name :" + go.name);
			
		}
		
		HudManager.Instance.SetCharInfo(_SID);
			
		
		if( IsPCType(pawnType) || pawnType == (int)GAME_PAWN_TYPE.AI || pawnType == (int)GAME_PAWN_TYPE.BOSS)
		{
			int nOrder = 1;
			totalPlayerCount++;
			if(!isMe) 
			{
				nPCCount++;
				nOrder = nPCCount;
			}
			
			thisPerson.order = nOrder;
			if(nOrder>=1 && nOrder<=4)
			{
				//CardManager.Instance.CreateDeck(_SID);
				bool isBoss = false;
				bool is2PlayerOnly = false;
				if( pawnType == (int)GAME_PAWN_TYPE.BOSS )
				{
					m_BossSID = _SID;
					nOrder = 3;
					thisPerson.order = nOrder;
					thisPerson.gameOrder = nOrder;
					isBoss = true;
					thisPerson.isBoss = true;
					MainHUDUI.Instance.SetPlayerTagStart(nOrder-1,isBoss);
				}
				else if(nOrder==2 && BoardManager.Instance.runnerCnt==2)
				{
				//	MainHUDUI.Instance.SetPlayerTagStart(nOrder-1,isBoss);
					is2PlayerOnly = true;
					nOrder = 3;
					thisPerson.order = nOrder;
					thisPerson.gameOrder = nOrder;
				}
				//else
				//	MainHUDUI.Instance.SetPlayerTagStart(nOrder-1,isBoss);

				thisPerson.gameOrder = thisPerson.order;
				
				thisPerson.isRetired = bIsRetire;
				if( thisPerson.isRetired )
					thisPerson.SetRetireTransparent();
				if(CSceneManager.gameStatus == GameStatus.GS_PLAYING)
					thisPerson.ReCalculateZ(true);
				if(thisPerson.isMe)
				{
					MainHUDUI.Instance.SetPlayerTagStart(nOrder-1,isBoss);
					HudManager.Instance.InitPanel(_SID, nOrder, nLevel, pw.Instance.Nickname, thisPerson.charID, isBoss, is2PlayerOnly, thisPerson.pawnType);

					//MakeGroundTag(thisPerson, nOrder);
				}
				else
					HudManager.Instance.MakePanelAdvance(nOrder);

			}
			else
			{
				GameObject playerName_go = Instantiate(BoardManager.Instance.playerNamePrefab) as GameObject;
				playerName_go.transform.parent = go.transform;
				if( IsPCType(pawnType) )
					playerName_go.transform.localPosition = new Vector3(0, 0.100f, go.transform.position.z);
				else
					playerName_go.transform.localPosition = new Vector3(0, 0.070f, go.transform.position.z);
				playerName_go.GetComponent<tk2dTextMesh>().text = "P"+nPawnCreated;		
				if(true) {//BoardManager.Instance.nameTagColors.Count==0) {
					Color c = new Color( UnityEngine.Random.Range(0.5f,1.0f), UnityEngine.Random.Range(0.5f,1.0f), UnityEngine.Random.Range(0.5f,1.0f), 1.0f);
					playerName_go.GetComponent<tk2dTextMesh>().color = c;
				}
				else {
					int index = UnityEngine.Random.Range(0, BoardManager.Instance.nameTagColors.Count);
					playerName_go.GetComponent<tk2dTextMesh>().color = BoardManager.Instance.nameTagColors[index];
					BoardManager.Instance.nameTagColors.RemoveAt(index);
				}
				
				playerName_go.GetComponent<tk2dTextMesh>().Commit();
				thisPerson.myNameTagColor = playerName_go.GetComponent<tk2dTextMesh>().color;		
			}
		}
		else
		{
			//MainHUDUI.Instance.SetActiveTag(0, thisPerson, pw.Instance.Nickname);
		}
		
        pw.BoardPerson = thisPerson;
		objectMap.Add (pw.SID, go);
		if(IsNPCType(pawnType))
		{
			BoardManager.Instance.boardPersonNPCList.Add( thisPerson );
			//go.SetActive(false);
		}
		else
			BoardManager.Instance.boardPersonPCList.Add( thisPerson );
		
		if(isMe) 
		{
			BoardManager.Instance.boardPerson_me = thisPerson;
			
			int btnIndex=0;
//			foreach( CSkillData skill in  pw.Instance.LeaderActiveSkillList)
//			{
//				BoardManager.Instance.boardPerson_me.skillList.Add (skill);
//				btnIndex++;
//			}	
//			MainHUDUI.Instance.skillNum = btnIndex;
		}
		
		MainHUDUI.Instance.AddTeam( _SID, isMe);
		
		
		if(bTurnStarted && IsNPCType(pawnType))
		{
			BoardManager.Instance.hidedSpawnNPC = thisPerson;
			thisPerson.shadow.renderer.enabled=false;
			thisPerson.isFalling = true;
			go.renderer.enabled = false;
			thisPerson.tagPerson.SetVisibleTagName(false);
			
			BoardTile bt = PathManager.Instance.GetBoardTile(_startBoard);
			
			if(bt.personOn.Count>0 && isTrapDecoy)
			{
				thisPerson.ShowHidedSpawnNPC(isTrapDecoy);
			}
			else
			{
				BoardPerson curTurnPerson = GetBoardPerson(BoardManager.Instance.curTurnSID);
				if(curTurnPerson!=null && !curTurnPerson.IsMovingOrWaitMoving() )
					thisPerson.ShowHidedSpawnNPC(isTrapDecoy);
			}

		}
		
	}

	public static void MakeGroundTag(BoardPerson thisPerson, int nOrder)
	{
		GameObject groundTag = NGUITools.AddChild(thisPerson.gameObject, IngameSetting.Instance.playerTagCirclePrefab);
		groundTag.transform.localPosition = IngameSetting.Instance.playerTagCirclePrefab.transform.localPosition;
		groundTag.transform.localRotation = IngameSetting.Instance.playerTagCirclePrefab.transform.localRotation;
		groundTag.transform.localScale = IngameSetting.Instance.playerTagCirclePrefab.transform.localScale;
		groundTag.GetComponent<ParticleSystem>().startColor = IngameSetting.Instance.p_color[nOrder-1];
		thisPerson.groundTag = groundTag;
	}
	
	public static void PP_RollMoveDiceResult(PC_OP_ROLL_MOVE_DICE_RESULT packet)
	{
		glog.debug("sid:"+packet.ServerID+" OP_ROLL_MOVE_DICE_RESULT OP_ROLL_MOVE_DICE_RESULT");
		//glog.debug("sid:"+packet.ServerID+ " ROLL_MOVE_DICE: " + packet.RollDiceCount+ " "+ packet.RollBonusValue);

		SkillManager.Instance.WaitSelectTarget(false);
		BoardManager.Instance.nCurTurn++;
		BoardManager.Instance.curTurnSID = packet.ServerID;
		camControl.EventZoomIn();
		camControl.SetCameraFocus(objectMap[packet.ServerID].transform);
		int sumRollValue = 0;
		foreach( int rollValue in packet.RollValueList) {
			sumRollValue += rollValue;
			glog.debug("sid:"+packet.ServerID+ " ROLL_MOVE_DICE: "+rollValue);
		}
		if(packet.RollBonusValueList!=null) 
		{
			foreach( int rollBonus in packet.RollBonusValueList) 
			{
				sumRollValue += rollBonus;
				if(rollBonus>0)
					glog.debug("roll bonus="+rollBonus);
			}
		}
		BattleManager.Instance.bCombatHappened = false;
		BoardPerson person = objectMap[packet.ServerID].GetComponent<BoardPerson>();
		person.bUseSkill_TileLift = false;
		
		if(!person.bCastedSkill)
			person.DeterminAnimFromCurTile(false);
		
		person.totalMoveCount = sumRollValue;
		person.remainMoveCount = person.totalMoveCount;
		person.nCurTurn = BoardManager.Instance.nCurTurn;
		//MainHUDUI.Instance.ShowUnitUI(packet.ServerID, objectMap[packet.ServerID].GetComponent<BoardPerson>());
		BoardManager.Instance.ShowDiceUI(person, packet.RollValueList, packet.RollBonusValueList, false);		
	}
	
	public static void PP_CombatResult(PC_OP_COMBAT_RESULT packet)
	{
//		if( packet.WinnerID == BoardManager.Instance.mySID || packet.LoserID == BoardManager.Instance.mySID)
//		{
//			MainHUDUI.Instance.ShowUnitUI(packet.WinnerID, objectMap[packet.WinnerID].GetComponent<BoardPerson>() );
//			MainHUDUI.Instance.ShowUnitUI(packet.LoserID, objectMap[packet.LoserID].GetComponent<BoardPerson>());
//		}
		UIManager.Instance.ClearBattleRoll();
		
		Camera.main.gameObject.GetComponent<CameraControl>().isPreventChangeFocus = true;
		
		if( BoardManager.Instance.curTurnSID == packet.WinnerID)
			GetBoardPerson(BoardManager.Instance.curTurnSID).SetCombatOpponent(true,GetBoardPerson(packet.LoserID));
		else if( BoardManager.Instance.curTurnSID == packet.LoserID)
			GetBoardPerson(BoardManager.Instance.curTurnSID).SetCombatOpponent(false,GetBoardPerson(packet.WinnerID));
	
		glog.debug ("BattlePacketProcess winner="+packet.WinnerID+" loser="+packet.LoserID);		
		glog.debug ("Attacker diceCount="+packet.AttackerDiceCount);
		glog.debug("CanGetBonus  a="+packet.AttackerCanGetBonus+"  d="+packet.DefenderCanGetBonus);
		int AttackerBonus = 0;
		int DefenderBonus = 0;
		int AttackerDice = 0;
		int DefenderDice = 0;
		for (int i = 0; i < packet.AttackerDiceCount; i++)
		{
			glog.debug("dice [" + i + "] -- " + packet.AttackerValueList[i]);
			AttackerDice += packet.AttackerValueList[i];
			BattleManager.Instance.SetAttackerDice(i,packet.AttackerValueList[i], packet.AttackerDiceCount);
		}
	
		//glog.debug("Attacker bonusCount=" + packet.AttackerBonusCount);
		for (int i = 0; i < packet.AttackerBonusCount; i++)
		{
			glog.debug("Attacker bonus [" + i + "] -- " + packet.AttacketBonusValueList[i]);
			AttackerBonus += packet.AttacketBonusValueList[i];
		}
	
		glog.debug("Defender diceCount=" + packet.DefenderDiceCount);
		for (int i = 0; i < packet.DefenderDiceCount; i++)
		{
			glog.debug("dice [" + i + "] -- " + packet.DefenderValueList[i]);
			DefenderDice += packet.DefenderValueList[i];
			BattleManager.Instance.SetDefenderDice(i,packet.DefenderValueList[i], packet.DefenderDiceCount);
		}
	
		//glog.debug("Defender bonusCount=" + packet.DefenderBonusCount);
		for (int i = 0; i < packet.DefenderBonusCount; i++)
		{
			glog.debug("Defender bonus [" + i + "] -- " + packet.DefenderBonusValueList[i]);
			DefenderBonus += packet.DefenderBonusValueList[i];
		}
	
		glog.debug("Attacker AddDice=" + packet.AttackerDiceAddCount);
		BattleManager.Instance.attackerAddDiceCount = packet.AttackerDiceAddCount;
		for (int i = 0; i < packet.AttackerDiceAddCount; i++)
		{
			glog.debug("Attacker - Add [" + i + "] -- " + packet.AttackerDiceAddList[i]);
			BattleManager.Instance.SetAttackerAddDice(i,packet.AttackerDiceAddList[i], packet.AttackerDiceAddCount);
		}
	
		glog.debug("Attacker DelDice=" + packet.AttackerDiceDelCount);
		BattleManager.Instance.attackerDelDiceCount = packet.AttackerDiceDelCount;
		for (int i = 0; i < packet.AttackerDiceDelCount; i++)
		{
			glog.debug("Attacker - Del [" + i + "] -- " + packet.AttackerDiceDelList[i]);
			BattleManager.Instance.SetAttackerDelDice(i,packet.AttackerDiceDelList[i], packet.AttackerDiceDelCount);
		}
	
		glog.debug("Attacker SwapDice=" + packet.AttackerDiceSwapCount);
		BattleManager.Instance.attackerSwapDiceCount = packet.AttackerDiceSwapCount;
		for (int i = 0; i < packet.AttackerDiceSwapCount; i++)
		{
			glog.debug("Attacker - Give [" + i + "] -- " + packet.AttackerDiceGiveList[i]);
			glog.debug("Attacker - Get [" + i + "] -- " + packet.AttackerDiceGetList[i]);
			BattleManager.Instance.SetAttackerSwapDice(i, packet.AttackerDiceGiveList[i], packet.AttackerDiceGetList[i], packet.AttackerDiceSwapCount);
		}
	
		glog.debug("Defender AddDice=" + packet.DefenderDiceAddCount);
		BattleManager.Instance.defenderAddDiceCount = packet.DefenderDiceAddCount;
		for (int i = 0; i < packet.DefenderDiceAddCount; i++)
		{
			glog.debug("Defender - Add [" + i + "] -- " + packet.DefenderDiceAddList[i]);
			BattleManager.Instance.SetDefenderAddDice(i,packet.DefenderDiceAddList[i], packet.DefenderDiceAddCount);
		}
	
		glog.debug("Defender DelDice=" + packet.DefenderDiceDelCount);
		BattleManager.Instance.defenderDelDiceCount = packet.DefenderDiceDelCount;
		for (int i = 0; i < packet.DefenderDiceDelCount; i++)
		{
			glog.debug("Defender - Del [" + i + "] -- " + packet.DefenderDiceDelList[i]);
			BattleManager.Instance.SetDefenderDelDice(i,packet.DefenderDiceDelList[i], packet.DefenderDiceDelCount);
		}
	
		glog.debug("Defender SwapDice=" + packet.DefenderDiceSwapCount);
		BattleManager.Instance.defenderSwapDiceCount = packet.DefenderDiceSwapCount;
		for (int i = 0; i < packet.DefenderDiceSwapCount; i++)
		{
			glog.debug("Defender - Give [" + i + "] -- " + packet.DefenderDiceGiveList[i]);
			glog.debug("Defender - Get [" + i + "] -- " + packet.DefenderDiceGetList[i]);
			BattleManager.Instance.SetDefenderSwapDice(i,packet.DefenderDiceGiveList[i],packet.DefenderDiceGetList[i],  packet.DefenderDiceSwapCount);
		}
	
		BattleManager.Instance.isDrawVicroty = false;
		BattleManager.Instance.isDrawDefeat = false;
		BattleManager.Instance.attackedSID = -1;
		BattleManager.Instance.deltaHPByAttack = 0;			
		BattleManager.Instance.attackedSlot = -1;
		BattleManager.Instance.winnerID = packet.WinnerID;
		BattleManager.Instance.loserID = packet.LoserID;
		BattleManager.Instance.combatHappenBoardID = packet.BoardID;
		BattleManager.Instance.bCombatHappened = true;
		BattleManager.Instance.elementBattleEnded = false;
		BattleManager.Instance.isDuringBattle = true;
		//GetBoardPerson(packet.AttackerID).isBattleResultDone = false;
		//GetBoardPerson(packet.DefenderID).isBattleResultDone = false;
		glog.debug("attacker multiply value "+packet.AttackerMultipleValueBySameDice);
		glog.debug("defender multiply value "+packet.DefenderMultipleValueBySameDice);
		BattleManager.Instance.isBattleResultDone = false;
		BattleManager.Instance.isWinnerActionDone = false;
		BattleManager.Instance.isLoserActionDone = false;
		BattleManager.Instance.attackColor = objectMap[packet.AttackerID].GetComponent<BoardPerson>().myNameTagColor;
		BattleManager.Instance.defenderColor = objectMap[packet.DefenderID].GetComponent<BoardPerson>().myNameTagColor;
		BattleManager.Instance.SetAttackerDefender( GetBoardPerson(packet.AttackerID), GetBoardPerson(packet.DefenderID), packet.AttackerMultipleValueBySameDice, packet.DefenderMultipleValueBySameDice);
		BattleManager.Instance.SetAttackerBonusDice( packet.AttackerID , packet.AttacketBonusValueList, packet.AttackerBonusCount);
		BattleManager.Instance.SetDefenderBonusDice( packet.DefenderID, packet.DefenderBonusValueList, packet.DefenderBonusCount);
		BattleManager.Instance.CheckShowBattleResult(AttackerDice, DefenderDice, packet.AttackerCanGetBonus, packet.DefenderCanGetBonus,  objectMap[packet.WinnerID].transform.position);		
	}

	void ProcessCombatResult( PC_OP_COMBAT_RESULT packet)
	{
		if(CardManager.Instance.isCoBattleEndRunning)
		{
			StartCoroutine( CoProcessCombatResult(packet) );
			return;
		}

		if(!bTurnStarted)
		{
			GetBoardPerson(packet.WinnerID).isTeleportDoing = false;
			GetBoardPerson(packet.LoserID).isTeleportDoing = false;
		}

		glog.debug (packet.WinnerID+" "+packet.LoserID+" OP_COMBAT_RESULT    ");
		BattleManager.Instance.maxCombatCount++;

		if(BattleManager.Instance.maxCombatCount>1)
		{
			glog.debug("Reserve combat packet "+BattleManager.Instance.maxCombatCount);
			BattleManager.Instance.ReserveCombatPacket(packet);
		}
		else
		{
			CardManager.Instance.maxCombatCount = BattleManager.Instance.maxCombatCount;
			PP_CombatResult(packet);
		}
	}

	IEnumerator CoProcessCombatResult( PC_OP_COMBAT_RESULT packet)
	{
		while(CardManager.Instance.isCoBattleEndRunning)
			yield return null;
		ProcessCombatResult(packet);
	}

	IEnumerator CoProcessBattleDiceUI(PC_SC_SHOW_UI packet, UIType uiType)
	{
		UIManager.Instance.ClearBattleRoll();
		rollCombatDiceSID = packet.ServerID;
		if(packet.Value!=0)
			showUI_attackerID = packet.Value;
		if(packet.Value2!=0)
			showUI_defenderID = packet.Value2;
		DateTime deadLine = new DateTime(packet.TimeStamp).AddTicks(-CSceneManager.TimeOffset);
		combatRollDeadLine = deadLine;
		
		BoardManager.Instance.bWaitForUIBattleDice = true;
		
		if(BattleManager.Instance.isDuringBattle)
		{
			//if( uiType == UIType.UI_ROLL_ATTACK_DICE)
			//	BoardManager.Instance.ActivateDiceOverHead( GetBoardPerson(packet.ServerID) );
			if( uiType == UIType.UI_ROLL_DEFENCE_DICE)
			{
				while(!BattleManager.Instance.bDiceRolledDuringBattle)
					yield return null;
				
				//BattleManager.Instance.bDiceRolledDuringBattle = false;
                if (packet.ServerID == m_MySID)
                    UIManager.Instance.ShowUIBattleRoll(true, deadLine, DiceShapeType.Defender);
                else
                {
                    // 희소 카운팅 진입점
                   
                }
				BoardManager.Instance.ActivateDiceOverHead( GetBoardPerson(packet.ServerID) , DiceShapeType.Defender);
			}
			
		}
		else
		{
			if( showUI_attackerID == packet.ServerID)// is attacker
			{
				glog.debug("attacker battle roll");
				BoardManager.Instance.isAttackerBattleRolled = true;
				GetBoardPerson(packet.ServerID).bWaitCombatRoll_attacker = true;
				GetBoardPerson(packet.ServerID).battleDeadLine = deadLine;
			}
			else
			{
				if(BoardManager.Instance.isAttackerAIThinkingShowed || BoardManager.Instance.isAttackerBattleRolled)
					BoardManager.Instance.ActivateDiceOverHead( GetBoardPerson(packet.ServerID) , DiceShapeType.Defender);

                if (packet.ServerID == m_MySID)
                {
                    glog.debug("defender battle roll  " + BoardManager.Instance.isAttackerBattleRolled);
                    if (BoardManager.Instance.isAttackerBattleRolled)
                    {
                        BoardManager.Instance.isAttackerBattleRolled = false;
                        UIManager.Instance.ShowUIBattleRoll(true, deadLine, DiceShapeType.Defender);
                    }
                    else
                    {
                        GetBoardPerson(showUI_attackerID).battleDeadLine = deadLine;
                        if (GetBoardPerson(showUI_attackerID).IsMovingOrWaitMoving())
                            GetBoardPerson(showUI_attackerID).bWaitCombatRoll_defender = true;
                        else
                            GetBoardPerson(showUI_attackerID).ShowDefenderDiceUI();

                    }
                }
                else
                {
                    // 희소 카운팅 진입점                   
                }			
			}
		}
	}
	
	void ProcessShowUI(PC_SC_SHOW_UI packet)
	{
		UIType uiType = (UIType)packet.UIType;
        Debug.LogWarning("<color=YELLOW>" +uiType.ToString() + "</color>");

		if (uiType == UIType.UI_COUNTDOWN && BoardManager.Instance.gameStarted)
		{
			glog.debug("GAME START countdown "+packet.Value);
			if( packet.Value2 == (int)CountDownType.LOAD_WAIT )
			{
				UIManager.Instance.GameStart(packet.Value);
			}
			else if( packet.Value2 == (int)CountDownType.ORDER_WAIT )
			{
				UIManager.Instance.SetCountDownForChooseGameOrder(packet.Value);
			}
		}
		
		if( !IsPawnCreated(packet.ServerID) )
			return;
		strLog = String.Format("sid={0} SHOW_UI : {1}  value={2}   value2={3}",packet.ServerID,uiType, packet.Value, packet.Value2);
		glog.debug(strLog);
		//RuntimeLog.Log(strLog);
		//if(!bTurnStarted)
		//	return;

        if (uiType == UIType.UI_ROLL_MOVE_DICE)
        {
            if (!objectMap[packet.ServerID].GetComponent<BoardPerson>().isMe)
            {
                // 희소 상대편 시간컨트롤   
                DateTime deadLine = new DateTime(packet.TimeStamp).AddTicks(-CSceneManager.TimeOffset);
                double totalSeconds = deadLine.Subtract(DateTime.UtcNow).TotalSeconds;
				HudManager.Instance.StartGageAni(packet.ServerID, (float)totalSeconds);
                return;
            }

				
			UIManager.Instance.ClearBattleRoll();
		//	UIManager.Instance.StartSliderTimer();
			UIManager.Instance.m_pawnWrapper = objectMap[packet.ServerID].GetComponent<CPawnWrapper>();
			if( objectMap[packet.ServerID].GetComponent<BoardPerson>().IsMovingOrWaitMoving() )
				objectMap[packet.ServerID].GetComponent<BoardPerson>().bWaitForExtraTurn = true;
			else
			{
				if (CSceneManager.UserInputMode == 0)
				{
					BoardManager.Instance.ShowUIRollMoveDice();
				}
				else if (CSceneManager.UserInputMode == 1 || CSceneManager.UserInputMode == 2)
				{
					DateTime deadLine = new DateTime(packet.TimeStamp).AddTicks(-CSceneManager.TimeOffset);
					BoardManager.Instance.ShowUIRollMoveDice(deadLine);
				}
			}
			
        }
        else if (uiType == UIType.UI_ROLL_DIRECTION_DICE)
        {
			// direction roll
			GetBoardPerson(packet.ServerID).bWaitActivateDiceOverHead = true;
			if(!GetBoardPerson(packet.ServerID).isMe)
			{
                // 희소 상대편 시간컨트롤   
                DateTime deadLine = new DateTime(packet.TimeStamp).AddTicks(-CSceneManager.TimeOffset);
                double totalSeconds = deadLine.Subtract(DateTime.UtcNow).TotalSeconds;
				HudManager.Instance.StartGageAni(packet.ServerID, (float)totalSeconds);


                if (!GetBoardPerson(packet.ServerID).IsMovingOrWaitMoving())
                {
                    GetBoardPerson(packet.ServerID).bWaitActivateDiceOverHead = false;
                    BoardManager.Instance.ActivateDiceOverHead(GetBoardPerson(packet.ServerID), DiceShapeType.Normal);
                }
                else
                {
                    // 희소 상대편 시간컨트롤
                }
				return;
			}
			objectMap[packet.ServerID].GetComponent<BoardPerson>().WaitShowDirectionRollUI();
			objectMap[packet.ServerID].GetComponent<BoardPerson>().directionRollDeadLine = new DateTime(packet.TimeStamp).AddTicks(-CSceneManager.TimeOffset);
        }
        else if (uiType == UIType.UI_YOU_WIN)
        {
			if(!objectMap[packet.ServerID].GetComponent<BoardPerson>().isMe)
				return;
		//	glog.debug (" SHOW_UI : UI_YOU_WIN");
	//		UIManager.Instance.HideBattleRoll();
	//		BattleManager.Instance.nTypeBattleResultUI = 1;
            //GameObject go = Instantiate(BoardManager.Instance.battleWinPrefab) as GameObject;
        }
        else if (uiType == UIType.UI_YOU_LOSE)
        {
			if(!objectMap[packet.ServerID].GetComponent<BoardPerson>().isMe)
				return;
	//		glog.debug (" SHOW_UI : UI_YOU_LOSE");
	//		UIManager.Instance.HideBattleRoll();
	//		BattleManager.Instance.nTypeBattleResultUI = 2;
            //GameObject go = Instantiate(BoardManager.Instance.battleLosePrefab) as GameObject;
        }
        else if (uiType == UIType.UI_ROLL_ATTACK_DICE || uiType == UIType.UI_ROLL_DEFENCE_DICE)
        {
            if (!GetBoardPerson(packet.ServerID).isMe)
            {
                 // 희소 상대편 시간컨트롤   
                DateTime deadLine = new DateTime(packet.TimeStamp).AddTicks(-CSceneManager.TimeOffset);
                double totalSeconds = deadLine.Subtract(DateTime.UtcNow).TotalSeconds;
				HudManager.Instance.StartGageAni(packet.ServerID, (float)totalSeconds);
            }


            StartCoroutine(CoProcessBattleDiceUI(packet, uiType));

	//		glog.debug (" SHOW_UI : UI_ROLL_COMBAT_DICE");


		//	objectMap[packet.ServerID].GetComponent<BoardPerson>().bCanCombatRoll = true;
		//	UIManager.Instance.StartSliderTimer();
			//objectMap[packet.ServerID].GetComponent<CPawnWrapper>().CanRoll = true;
			//UIManager.Instance.CanRoll(objectMap[packet.ServerID].GetComponent<CPawnWrapper>() );
        }
		else if(uiType == UIType.UI_AI_THINKING)
		{
			//if( BoardManager.Instance.boardPersonNPCList.Contains( GetBoardPerson(packet.ServerID) ) )
			//	return;

			bool bCombatState = false;
			int attackerSID = 0;
			int defenderSID = 0;
			if(packet.Value != 0 && packet.Value2 != 0)
			{
				bCombatState = true;
				rollCombatDiceSID = 0;
				attackerSID = packet.Value;
				defenderSID = packet.Value2;
			}


			if(bCombatState)
			{
				BoardManager.Instance.bWaitForUIBattleDice = true;
				battleAIThinkingSID = packet.ServerID;
				bAIBattleDiceRollImmediately = false;

				if( BattleManager.Instance.isDuringBattle)
				{
					if(attackerSID == packet.ServerID)
						BattleManager.Instance.bWaitAIThinking = true;
					else
					{
						bAIBattleDiceRollImmediately = true;
						BoardManager.Instance.ActivateDiceOverHead( GetBoardPerson(packet.ServerID) , DiceShapeType.Defender);
					}
				}
				else
				{
					if(attackerSID == packet.ServerID)
					{
						if( GetBoardPerson(packet.ServerID).IsMovingOrWaitMoving() )
						{
							BoardManager.Instance.isAttackerAIThinkingShowed = false;
							GetBoardPerson(packet.ServerID).bWaitActivateDiceOverHead_aibattle = true;
						}
						else
						{
							BoardManager.Instance.isAttackerAIThinkingShowed = true;
							bAIBattleDiceRollImmediately = true;
							BoardManager.Instance.ActivateDiceOverHead( GetBoardPerson(packet.ServerID) ,DiceShapeType.Attacker);
						}
					}
					else
					{
						if(BoardManager.Instance.isAttackerAIThinkingShowed || BoardManager.Instance.isAttackerBattleRolled)
						{
							bAIBattleDiceRollImmediately = true;
							BoardManager.Instance.ActivateDiceOverHead( GetBoardPerson(packet.ServerID) ,DiceShapeType.Defender);
						}
						else 
							BoardManager.Instance.bWaitDefenderAIThink = true;
					}
				}
			}
			else
			{
				if( GetBoardPerson(packet.ServerID).IsMovingOrWaitMoving() )
					GetBoardPerson(packet.ServerID).bWaitActivateDiceOverHead = true;
				else
				{
					GetBoardPerson(packet.ServerID).bWaitActivateDiceOverHead = false;
					BoardManager.Instance.ActivateDiceOverHead( GetBoardPerson(packet.ServerID) , DiceShapeType.Normal);
				}
			}

		}
		else if(uiType == UIType.UI_COMBAT_REDICE)
		{
			BattleManager.Instance.isRedice = true;
		}
		else if(uiType == UIType.UI_COMBAT_REMATCH)
		{
			BattleManager.Instance.isRematch = true;
		}
		else if (uiType == UIType.UI_CHASE)
        {
	//		glog.debug (" SHOW_UI : UI_CHASE! sid="+packet.ServerID);
			objectMap[packet.ServerID].GetComponent<BoardPerson>().bChasing = true;
		}
		else if (uiType == UIType.UI_AVOID)
        {
	//		glog.debug (" SHOW_UI : UI_AVOID! sid="+packet.ServerID+"  target="+ packet.Value);
			// avoid target : packet.Value
			GetBoardPerson(packet.ServerID).avoidTargetList.Add( packet.Value );
		}
		else if (uiType == UIType.UI_BLOCK)
		{
	//		glog.debug(" SHOW_UI : UI_BLOCK! sid=" + packet.ServerID);
			//BoardManager.Instance.ShowUIOnPerson("Block!", GetBoardPerson(packet.ServerID));
			BoardManager.Instance.ShowUIOnPerson(UIType.UI_BLOCK, GetBoardPerson(packet.ServerID));
		}		
		else if(uiType == UIType.UI_ESCAPE_TO_BIND)
		{
			BoardManager.Instance.bEscapeToBind = true;
		}
		else if(uiType == UIType.UI_ESCAPE_FAIL_TO_BIND)
		{
			BoardManager.Instance.bEscapeFailToBind = true;
		}
		else if(uiType == UIType.UI_PUSHBACK_DELTA)
		{
			//BoardManager.Instance.bEscapeFailToBind = true;
			BattleManager.Instance.pushBackDelta = packet.Value;
		}
		else if(uiType == UIType.UI_DRAW_VICTORY)
		{
			BattleManager.Instance.isDrawVicroty = true;
		}		
		else if(uiType == UIType.UI_DRAW_DEFEAT)
		{
			BattleManager.Instance.isDrawDefeat = true;
		}
		else if(uiType == UIType.UI_CONFUSE)
		{
			GetBoardPerson(packet.ServerID).bUseSkill_BackMove = true;
		}
		else if(uiType == UIType.UI_RECOVER_MP)
		{
			//if(packet.Value>=2)
			//	GetBoardPerson(packet.ServerID).ShowMPRecoverEffect();	
		}
		else if(uiType == UIType.UI_CASE_RECOVER_MP)
		{
//			if(BoardManager.Instance.curTurnSID == packet.ServerID)
//				BoardManager.Instance.SetCaseRecoverMP(packet.Value);
//			else
//				BoardManager.Instance.SetOtherPlayerCaseRecov ㅂ115erMP(packet.ServerID, packet.Value);
		} 
        else if (uiType == UIType.UI_LAST_WAIT_TO_RESERRECTION)
        {
            Debug.LogError("Last wait");
			UIManager.Instance.deadLine = new DateTime(packet.TimeStamp).AddTicks(-CSceneManager.TimeOffset);
			Debug.LogError("deadLine.Ticks : " + UIManager.Instance.deadLine);
//			UIManager.Instance.ShowGameContinuCountDown(deadLine);
			UIManager.Instance.isCountDownShowing = true;
        }
		else if(uiType == UIType.UI_LEVEL_UP)
		{
//			string[] param = new string[1];
//			param[0] = packet.Value.ToString();
//			MessagePopup.window.ShowPopup(MESSAGEPOPUPTYPE.LevelUP, param, null);
			MyInfo.Instance.isLevelUp = true;
			MyInfo.Instance.nextUserLevel = packet.Value;

            Popup_Levelup.SetCash();  // 레벨업 팝업을 위한 케슁
		}
		else if(uiType == UIType.UI_GET_TEMP_SKILL)
		{
			if(bTurnStarted || bContinueTurnStarted)
			{
				GetBoardPerson(packet.ServerID).AchieveTempSkill(packet.Value);
			}
			else
			{
				if( !HudManager.Instance.tempSkillListByGameOrder.ContainsKey(packet.ServerID) )
					HudManager.Instance.tempSkillListByGameOrder.Add(packet.ServerID, packet.Value);
			}
		}
	}
	
	void ProcessUseSkill(int sid, int skillId, int targetId)
	{
		if( GetBoardPerson(sid).IsMovingOrWaitMoving() )
		{
			Debug.LogError("this should not happen.");// happen once. On changing pc->bot , use skill on the same time dice rolls. when this happens, person cannot move
			return;
		}
		UIManager.Instance.ShowMoveRollButton(false);
		bool bUseBuffEffect = false;
		bool bCameraToTarget = false;
		BoardManager.Instance.bWaitForSkillShow = true;
		if(skillId == 100011)
			GetBoardPerson(targetId).bUseSkill_ShuffleDeck = true;
		else if(skillId == 100006) {
			//CardManager.Instance.ShowSkillNameEffect("Card Activate");
			bUseBuffEffect = true;
			GetBoardPerson(sid).bUseSkill_ForceNextCard = true;
		}
		else if(skillId == 100010) {
			//CardManager.Instance.ShowSkillNameEffect("Card To Tomb");
			GetBoardPerson(targetId).bUseSkill_CardToTomb = true;
			//bCameraToTarget = true;
		}
		else if(skillId == 100005) {
			//CardManager.Instance.ShowSkillNameEffect("Skill CardResurrect");	
			bUseBuffEffect = true;
			GetBoardPerson(sid).bUseSkill_CardResurrect = true; 
		}
		else if(skillId == 100024)
		{
			//CardManager.Instance.ShowSkillNameEffect("Skill BackMove");
			
			
	//		GetBoardPerson(targetId).bUseSkill_BackMove = true;
			
			
			
			//bCameraToTarget = true;
		}
		else if(skillId == 100023)
		{
			//CardManager.Instance.ShowSkillNameEffect("Skill TileLift");
			GetBoardPerson(sid).bUseSkill_TileLift = true;
			GetBoardPerson(sid).timeTileLift = 0.4f;
		}
		else if(skillId == 100007)
		{
			//CardManager.Instance.ShowSkillNameEffect("Skill HP Restore");
			//GetBoardPerson(sid).bUsedHPRestoreEffect = true;
		}
		else if(skillId == 100013)
		{
		//	CardManager.Instance.ShowSkillNameEffect("Skill Avoid");
		}
		else if(skillId == 100018)
		{
		//	CardManager.Instance.ShowSkillNameEffect("Skill Berserk");
			UIManager.Instance.ShowSkillInfo( CStringTableManager.Instance.GetItemById(1699)  , true );
		}
		else if(skillId == 100016)
		{
		//	CardManager.Instance.ShowSkillNameEffect("Skill Teleport");
			BoardManager.Instance.bUsedTeleportSkill = true;
		}
		else if(skillId == 100015)
		{
			BoardManager.Instance.bUsedTrapDecoy = true;
		}
		else if(skillId == 100035)//player_seal_active_card_slot
		{
			Debug.LogError("player_seal_active_card_slot  target="+targetId);
			//GetBoardPerson(targetId).SetAbnormal(AbnormalType.SEAL_ACTIVE_CARD_SLOT,0);
		}
		//else if(skillId == 100017)
		//	GetBoardPerson(sid).bUseSkill_TileFrozen = true;
		UIManager.Instance.SkillNameShow(skillId);

		CSkillData skillData = CSkillDataManager.Instance.FindSkillData(skillId);
		bool isEnemyAll = false;
		if( skillData != null)
		{
			if(skillData.abnormalList.Count>0)
			{
				glog.debug(skillData.abnormalList.Count+"  skill abnormal type="+  skillData.abnormalList[0].Type+" value="+skillData.abnormalList[0].GetValue() );
				SkillManager.Instance.LoadResource(skillId, skillData.abnormalList[0].Type, skillData.abnormalList[0].GetValue());
			}
			else
				SkillManager.Instance.LoadResource(skillId, AbnormalType.NONE, 0);
				//SkillManager.Instance.abnormal_SkillLink.Add( skillData.abnormalList
			if(skillData.target_type == target_type.Enemy_Select ||/* skillData.target_type == target_type.Enemy_Random ||*/ skillData.target_type == target_type.Enemy_All)
				bCameraToTarget = true;
			if(skillData.target_type == target_type.Enemy_All)
				isEnemyAll = true;
		}
		GetBoardPerson(sid).PlaySkillCastAnim(skillId, skillData, bUseBuffEffect, bCameraToTarget, GetBoardPerson(targetId), isEnemyAll);		
	}

	public void UpdateAbnormalState(BoardPerson person, PC_OP_CHANGE_ABNORMAL_EFFECT packet)
	{
		person.abnormalPacket = null;
		person.PreUpdateAbnormalState();
		//		glog.debug(packet.ServerID+"  abnormal count" + packet.AbnormalCount);
		
		for (int i = 0; i < packet.AbnormalCount; i++)
		{
			//			glog.debug("type " + packet.AbnormalTypeList[i]);
			//			glog.debug("value " + packet.AbnormalValueList[i]);
			AbnormalType abType = (AbnormalType)packet.AbnormalTypeList[i];
			Debug.LogError(person.SID+" abnormal  "+abType+"  dur="+packet.AbnormalDurationList[i]+"  value="+packet.AbnormalValueList[i]+"  SkillID="+packet.SkillIDList[i] + "   Reason="+packet.AbnormalReasonList[i]);
			//			glog.debug("duration " + packet.AbnormalDurationList[i]);
			//			glog.debug("effectID " + packet.EffectIDList[i]);


            person.SetAbnormal(abType, packet.AbnormalValueList[i], packet.AbnormalDurationList[i], (EffectReason)packet.AbnormalReasonList[i], packet.SkillIDList[i]);
			/*
				if(packet.AbnormalTypeList[i] == (int)AbnormalType.BIND) 
				{
					if( objectMap[packet.ServerID].GetComponent<BoardPerson>().IsMovingOrWaitMoving())
					{
						glog.debug("reserve bind "+packet.ServerID);
						objectMap[packet.ServerID].GetComponent<BoardPerson>().isToBeBound = true;
					}
					else {
						if(m_curTurn == GetBoardPerson(packet.ServerID).m_myTurn)
						{
							if(packet.ServerID != m_MySID)
								camControl.SetCameraFocus( GetBoardPerson(packet.ServerID).transform );
							objectMap[packet.ServerID].GetComponent<BoardPerson>().ShowBoundObject();
						}
					}
				}
				else if(packet.AbnormalTypeList[i] == (int)AbnormalType.SLEEP) 
				{
					person.SetAbnormal(AbnormalType.SLEEP);
				}
				else if(packet.AbnormalTypeList[i] == (int)AbnormalType.SEAL_ACTIVE_CARD_SLOT) {
					//person.abnormalSealActiveCard = true;
					person.SetAbnormal(AbnormalType.SEAL_ACTIVE_CARD_SLOT);
				}
				*/
		}
		
		person.AfterUpdateAbnormalState();
	}

	void ProcessAbnormalEffect(PC_OP_CHANGE_ABNORMAL_EFFECT packet)
	{
		if( !IsPawnCreated(packet.ServerID) )
			return;
		Debug.LogError(packet.ServerID+"  -- OP_CHANGE_ABNORMAL_EFFECT "+packet.AbnormalCount);
		BoardPerson person = GetBoardPerson(packet.ServerID);
		//person.abnormalStateList.Clear();
		//person.abnormalSealActiveCard = false;
		if(person.IsMovingOrWaitMoving())
		{
			glog.debug("person is moving...wait for stop");
			person.abnormalPacket = packet;
		}
		else if(BattleManager.Instance.bCombatHappened && !BattleManager.Instance.elementBattleEnded)
		{
			glog.debug("wait for element battle done");
			person.abnormalPacket = packet;
		}
		else
		{
			UpdateAbnormalState(person, packet);
		}
		//UIManager.Instance.bUseSkill = false;
	}

	public void UpdateTeamData(PC_OP_UPDATE_TEAM_DATA packet)
	{
		glog.debug("OP_UPDATE_TEAM_DATA sid="+packet.ServerID);
		if (true)
		{
			int mp = -1;
			int maxmp = -1;
			int lapcount = -1;
			for (int i = 0; i < packet.DataCount_team; i++)
			{
				int slot = 0;
				int hp = 0;
				int maxhp = 0;		
				
				switch (  packet.KeyList_team[i]  )
				{
				case (byte)ParameterType.PT_MP:
					//tmpPawn.MP = (int)packet.DataList[i];
					mp = (int)packet.DataList_team[i];
					glog.debug("MP : " + mp);
					break;
				case (byte)ParameterType.PT_MAX_MP:
					//tmpPawn.MP = (int)packet.DataList[i];
					maxmp = (int)packet.DataList_team[i];
					glog.debug("Max MP : " + maxmp);
					break;
				case (byte)ParameterType.PT_HP:
					hp = (int)packet.DataList_team[i];
					glog.debug("ID:"+packet.ServerID+"  slot:"+slot+"  HP : " + hp);
					HudManager.Instance.SetHP(packet.ServerID, slot, hp);
					break;
				case (byte)ParameterType.PT_MAX_HP:
					maxhp = (int)packet.DataList_team[i];
					glog.debug("ID:"+packet.ServerID+"  slot:"+slot+ "  MAXHP : " + maxhp);
					HudManager.Instance.SetMaxHP(packet.ServerID, slot,maxhp);
					break;
				case (byte)ParameterType.PT_LAP:
					lapcount = (int)packet.DataList_team[i];
					
					break;
				default:
					glog.debug("Unknown ParameterType --- " + packet.KeyList_team[i]);
					break;
				}
			}
			if(lapcount!=-1)
				GetBoardPerson(packet.ServerID).SetLapCount(lapcount);
			if(mp!=-1 && maxmp!=-1)
			{
				HudManager.Instance.SetMaxMP(packet.ServerID, maxmp );
				HudManager.Instance.SetMainCharMP(packet.ServerID, mp, true);
			}
		}
	}

	void ProcessShowChangeHP(PC_SC_SHOW_CHANGE_HP packet)
	{
		HPModReason hpModReason = (HPModReason) packet.HPModReason;
		Debug.LogError( String.Format("SID:{0} SC_SHOW_CHANGE_HP  reason={1} bid={2}",packet.ServerID, hpModReason, packet.BoardID) ); 

		bool isRebirth = false;
		
		int slot = 0;
		int before_hp = packet.BeforeHP;
		int deltahp = packet.DeltaHP;
		int afterhp = packet.AfterHP;
		if(before_hp==0 && deltahp>0)
			isRebirth = true;
		glog.debug("slot:"+slot+"  before="+before_hp+"  deltaHP=" + deltahp+"   afterHP="+afterhp);
		BoardPerson person = GetBoardPerson(packet.ServerID);		
		if( before_hp == afterhp)
			return;
		HudManager.Instance.AddHpChangeInfo(packet.ServerID, person, hpModReason, before_hp, deltahp, afterhp, packet.BoardID);
		HudManager.Instance.ShowHPChangeEffect_BySkill();


		/*
		if( HudManager.Instance.SetChangedHP(packet.ServerID, slot, before_hp, deltahp) )
		{
			if(BattleManager.Instance.bCombatHappened && packet.ServerID == BattleManager.Instance.loserID )
			{
				glog.debug("battle loser attacked");
				BattleManager.Instance.deltaHPByAttack = deltahp;
				BattleManager.Instance.attackedSID = packet.ServerID;
				BattleManager.Instance.attackedSlot = slot;
			}
		}	
		
		
		if(person.bUsedHPRestoreEffect)
		{
			person.bUsedHPRestoreEffect = false;
			HudManager.Instance.ShowHPEffect(person,  false, false);
		}
		if(isRebirth)
		{
			HudManager.Instance.ShowHPEffect(person,  false, true);
		}
		if( !BattleManager.Instance.bCombatHappened && !person.IsMovingOrWaitMoving() )//  hp change that happens on turn start( ex. card skill)
			HudManager.Instance.ShowHPEffect(person,  false, false);
		*/
	}

	void ProcessShowChangeMP(PC_SC_SHOW_CHANGE_MP packet)
	{
		Debug.LogError(String.Format("SHOW_CHANGE_MP SID[{0}] Before[{1}] After[{2}] Delta[{3}] Reason[{4}]", packet.ServerID, packet.BeforeMP, packet.AfterMP, packet.DeltaMP, (MPRegenType)packet.MPModReason));
		BoardPerson person = GetBoardPerson(packet.ServerID);
		HudManager.Instance.AddMpChangeInfo(packet.ServerID, person, (MPRegenType)packet.MPModReason, packet.BeforeMP, packet.DeltaMP, packet.AfterMP, packet.BoardID);
		HudManager.Instance.ShowMPChangeEffect_Instant();

	}

	public void UpdateUnitActivationInfo(PC_OP_UNIT_ACTIVATION_INFO packet)
	{
		if(!IsPawnCreated(packet.ServerID))
			return;
		UnitActivationReason reason = (UnitActivationReason)packet.Reason;

		if(bTurnStarted || bContinueTurnStarted)
			CardManager.Instance.CheckCardLocked(packet.ServerID, packet.ActiveSlot);

		BoardPerson person = GetBoardPerson(packet.ServerID);

		if(BattleManager.Instance.bCombatHappened)
		{
			if(reason == UnitActivationReason.BOARD)
				person.unitActivationPacketByBoard = packet;
			else
			{
				if(reason== UnitActivationReason.BY_COMBAT)
				{
					CardManager.Instance.ClearUnitActivationInfo(CardManager.Instance.maxCombatCount, packet.ServerID);
					for(int i=0; i< packet.ActiveQueueCount; i++)
					{
						glog.debug(CardManager.Instance.maxCombatCount+" battle active "+packet.ActiveQueue[i]);
						CardManager.Instance.AddActivationInfo(CardManager.Instance.maxCombatCount, packet.ServerID, packet.ActiveQueue[i]);
					}	
					CardManager.Instance.CheckAddActivationInfo(CardManager.Instance.maxCombatCount, packet.ServerID, false);
					for(int i=0; i< packet.DeactiveCount; i++)
					{
						glog.debug(CardManager.Instance.maxCombatCount+" battle deactive "+packet.DeactiveList[i]+ "   "+packet.DeactiveTurn[i]);
						CardManager.Instance.AddDeactivationInfo(CardManager.Instance.maxCombatCount, packet.ServerID, packet.DeactiveList[i], packet.DeactiveTurn[i]);
					}
				}
				else if(reason== UnitActivationReason.SKILL_EFFECT)
				{
					UnitActivationInfo_NonBattle(person, packet, reason);
				}
			}
		}
		else
		{
			if ( person.isRetired)
			{
				glog.debug("retired break");
				return;
			}
			if(!bTurnStarted || CardManager.Instance.isAddedTeam)
			{
				CardManager.Instance.ClearInfo_NonBattle(packet.ServerID);
				CardManager.Instance.ClearDeck_BeforeTurnStart(packet.ServerID);
				for(int i=0; i< packet.ActiveQueueCount; i++)
				{
					glog.debug("before turn active "+packet.ActiveQueue[i]);
					CardManager.Instance.CheckActiveList_BeforeTurnStart( packet.ServerID, packet.ActiveQueue[i]);
				}	
				for(int i=0; i< packet.DeactiveCount; i++)
				{
					glog.debug("before turn -- deactive "+packet.DeactiveList[i]+ "   "+packet.DeactiveTurn[i]);
					CardManager.Instance.CheckDeactiveInfo_BeforeTurnStart( packet.ServerID, packet.DeactiveList[i], packet.DeactiveTurn[i]);
				}
				if(CardManager.Instance.isAddedTeam)
					CardManager.Instance.isAddedTeam = false;
			}
			else
			{
				UnitActivationInfo_NonBattle(person, packet, reason);
			}
		}
	}

	void UnitActivationInfo_NonBattle(BoardPerson person, PC_OP_UNIT_ACTIVATION_INFO packet, UnitActivationReason reason)
	{
		if(person.bUseSkill_ShuffleDeck)
		{
			person.bUseSkill_ShuffleDeck = false;
			if(!CardManager.Instance.IsCardLocked(packet.ServerID) )
			{
				CardManager.Instance.Init_ShuffleDeck(packet.ServerID);
				for(int i=0; i< packet.ActiveQueueCount; i++)
				{
					glog.debug("shuffle active "+packet.ActiveQueue[i]);
					CardManager.Instance.AddShuffleDeck( packet.ServerID, packet.ActiveQueue[i]);
				}	
				CardManager.Instance.ShuffleDeck(packet.ServerID);
			}
		}
		else if(person.bUseSkill_ForceNextCard)
		{
			person.bUseSkill_ForceNextCard = false;
			if(!CardManager.Instance.IsCardLocked(packet.ServerID) )
			{		
				CardManager.Instance.Init_ForceNextCard(packet.ServerID);
				for(int i=0; i< packet.ActiveQueueCount; i++)
				{
					glog.debug("ForceNextCard active "+packet.ActiveQueue[i]);
					CardManager.Instance.Set_ForceNextCard( packet.ServerID, packet.ActiveQueue[i]);
				}	
				CardManager.Instance.ForceNextCardActivate(packet.ServerID);
			}
		}
		else if(person.bUseSkill_CardToTomb)
		{
			HudManager.Instance.ShowAIEmotionChat(packet.ServerID, "skill_bad");
			person.bUseSkill_CardToTomb = false;
			if(!CardManager.Instance.IsCardLocked(packet.ServerID) )
			{
				CardManager.Instance.Init_CardToTomb(packet.ServerID);
				for(int i=0; i< packet.ActiveQueueCount; i++)
				{
					glog.debug("CardToTomb active "+packet.ActiveQueue[i]);
					CardManager.Instance.SetActive_CardToTomb( packet.ServerID, packet.ActiveQueue[i]);
				}	
				for(int i=0; i< packet.DeactiveCount; i++)
				{
					glog.debug("CardToTomb -- deactive "+packet.DeactiveList[i]+ "   "+packet.DeactiveTurn[i]);
					CardManager.Instance.SetDeactive_CardToTomb( packet.ServerID, packet.DeactiveList[i], packet.DeactiveTurn[i]);
				}
				CardManager.Instance.ActiveCardToTomb(packet.ServerID);
			}
		}						
		else
		{
			if(person.bUseSkill_CardResurrect)
			{
				HudManager.Instance.ChangeFace(packet.ServerID, true);
				person.bUseSkill_CardResurrect = false;
				CardManager.Instance.SetUnitActivationInfo_NonBattle(packet);
			}
			else
			{
				if(reason== UnitActivationReason.BOARD)
					person.unitActivationPacketByBoard = packet;
				else
					CardManager.Instance.SetUnitActivationInfo_NonBattle(packet);
			}
		}
	}

	public static void RegGameObject(int SID, GameObject go)
	{
        objectMap.Add(SID, go);	
	}


	void FindPathToGoal()
	{
		bFindPathToGoal = true;
		PathManager.Instance.ClearPathToGoal();
		PathManager.Instance.FindPathToGoal(  BoardManager.Instance.boardPerson_me.curBoardTile.boardInfo.id);
		BoardManager.Instance.isShowDiceUIDone = true;
		//camControl.bUseCamLerp = false;
		BoardManager.Instance.boardPerson_me.moveSpeedManual = 2;
		BoardManager.Instance.StartMovePawn(BoardManager.Instance.boardPerson_me, PathManager.Instance.pathToGoal.Count, PathManager.Instance.pathToGoal.ToArray() , false);
		if(PathManager.Instance.candidateBid.Count>0)
		{
			foreach(int bid in PathManager.Instance.candidateBid)
				BoardManager.Instance.boardPerson_me.SetWaitingSelectPath(bid, new DateTime() );
		}
	}

	public void FindPathToGoal(int nid)
	{
		if(bPathRun)
		{
			PathManager.Instance.ClearPathToGoal();
			PathManager.Instance.FindPathToGoal( nid);
			BoardManager.Instance.boardPerson_me.moveSpeedManual = 2;
			BoardManager.Instance.StartMovePawn(BoardManager.Instance.boardPerson_me, PathManager.Instance.pathToGoal.Count, PathManager.Instance.pathToGoal.ToArray() , false);
			if(PathManager.Instance.candidateBid.Count>0)
			{
				foreach(int bid in PathManager.Instance.candidateBid)
					BoardManager.Instance.boardPerson_me.SetWaitingSelectPath(bid, new DateTime() );
			}
		}
	}
	
	public static void StartStage()
	{
		if (CNetworkManager.Instance.Connected)
        {
            CNetworkManager.Instance.SendRequest("PlayStart");
        }
        else
        {
            bPlaying = Instance.PlayStart();	
        }
	}

    internal static void SendReadyStatus(ReadyStatus readyStatus)
    {
        PC_OP_CHANGE_READY_STATUS packet = new PC_OP_CHANGE_READY_STATUS();

        //CNetworkManager.Instance.SendPacket(packet.Protocol, packet.GetParam());
		CNetworkManager.Instance.SendPacket(packet);
    }

    public void ReturnCallback(Hashtable returnData)
    {
        switch ((RestAPIProtocol)returnData["protocol"])
        {
            case RestAPIProtocol.REFRESHUSERINFO:
                RestAPI.singleton.GetMyUnitList(ReturnCallback);
                break;
            case RestAPIProtocol.GETMYUNITLIST:
				RestAPI.singleton.GetCurrentStaminaInfo(ReturnCallback);
                break;
			case RestAPIProtocol.GETCURRENTSTAMINAINFO:
                LoadingWindow.window.HideLoading();
				CSceneManager.manager.GoToWaitroomScene();
				break;
            case RestAPIProtocol.GETPVESTAGEINFO:
                break;
        }
    }

	public static void MessagePopupCallback(MESSAGEPOPUPTYPE type, bool isYes)
	{
		if (type == MESSAGEPOPUPTYPE.LevelUP )
			SendLeave();
	}
		
	void OnGUI()
	{
		if(CSceneManager.bShowPacketWaitingInfo)
		{
			GUI.color = Color.blue;
			GUI.Label(new Rect(Screen.width/3,3,400,20), strPacketWaitingInfo );
			if(bShowTimeElapsed)
			{
				GUI.color = Color.blue;
				GUI.Label(new Rect(10,3,40,20), String.Format("{0:0.00}",timeElapsedFromStart) );
				if(CSceneManager.isReplay)
				{
					GUI.Label(new Rect(100,3,40,20), String.Format("{0:0.00}",replayLastTime) );			
				}
			}
		}
	}
}
